开发者

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


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.


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?


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜