tags:

views:

153

answers:

4
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
    string a;
    cin>>a;
    a.erase(a.end()-1);
    a.erase(a.begin()+1);
    string ge = "oae";
    a.insert(a.begin()+1, ge);
    cout<<a<<endl;
    return 0;
}

It doesn't compile and i don't know why. Can you tell me what's wrong

+1  A: 

a.insert(a.begin()+1, ge); is the problem.

The string::insert function takes an int as the first parameter, and you're passing in an iterator. What are you trying to do?

David
No overload of std::basic_string<t>::insert takes an int parameter. Some overloads take `size_t` parameters, but not one takes an int.
Billy ONeal
David
@David: Size_t is a typedef for unsigned int on your compiler. The standard does not define it that way, however. That could be unsigned long, or unsigned long long, or unsigned short, or any other similar type and conform to standard.
Billy ONeal
+3  A: 

http://www.cplusplus.com/reference/string/string/insert/

string& insert ( size_t pos1, const string& str );
 string& insert ( size_t pos1, const string& str, size_t pos2, size_t n );
 string& insert ( size_t pos1, const char* s, size_t n);
 string& insert ( size_t pos1, const char* s );
 string& insert ( size_t pos1, size_t n, char c );
iterator insert ( iterator p, char c );
    void insert ( iterator p, size_t n, char c );
template<class InputIterator>
    void insert ( iterator p, InputIterator first, InputIterator last );

Your call to std::basic_string<t>::insert does not match any of the above overloads.

a.insert(a.begin()+1, ge);

needs to be

a.insert(a.begin()+1, ge.begin(), ge.end());

or

a.insert(1, ge);

Otherwise that code is not valid.

Billy ONeal
+1  A: 

Working version:

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
    string a;
    cin>>a;
    a.erase(a.end()-1);
    a.erase(a.begin()+1);
    string ge = "oae";
    a.insert(1, ge);          // here
    cout<<a<<endl;
    return 0;
}
harpun
+1 because it's correct and you're new, but in the future you're not likely to get upvoted just for posting corrected code. You need to explain why the code was incorrect to begin with.
Billy ONeal
+1  A: 

There's no std::string::insert() overload that takes an iterator and string set of parameters. You might chose instead to use:

a.insert( 1, ge);   // use an index and a string

or:

a.insert( a.begin()+1, ge.begin(), ge.end());  // use an destination iterator, and 
                                               //  a set of iterators indicating a range

Note that this will allow your code to compile, but it may have some runtime problems, such as:

  • if a is an empty string, then a.end()-1 is undefined
  • if a is an empty string, then a.begin()+1 is similarly undefined
Michael Burr