dada
dada

Reputation: 1105

What's wrong with the following code?

#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

Upvotes: 0

Views: 732

Answers (4)

Michael Burr
Michael Burr

Reputation: 340516

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

Upvotes: 1

harpun
harpun

Reputation: 4110

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;
}

Upvotes: 1

Billy ONeal
Billy ONeal

Reputation: 106609

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.

Upvotes: 3

David
David

Reputation: 7153

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?

Upvotes: 1

Related Questions