vector中的插入和排序,出了错误,不知道什么原因
本帖最后由 u011873969 于 2013-10-23 03:47:03 编辑 #include部分我就不写了。
这个程序要做的事情很简单:
首先输入一些单词组成的文章text,
然后将这文章中的所有单词按照字典顺序排序,
然后输出排序的结果,
然后电脑问用户是不是需要添加一些单词
然后用户输入任意多的单词,每输入一个,程序都会用按照字典顺序将其插入到text中,并输出排序的结果。
编译的时候没问题,但是运行的时候,到了while语句部分时,就会弹出窗口报错,说vector iterators incompatible,无法理解,自认为不会有这样的错误。哪位大神来解释一下子呢?
注:displayText是把一个vector<string>类型的变量中的所有元素输出的函数
iterator vector
int main()
{
vector<string> text;
string text_word;
cout<<"\nInput a text:\n";
while(cin>>text_word)
{
text.push_back(text_word);
}
cin.clear();
cout<<"\n--------So the text you have input is:\n";
displayText(text);
cout<<"\n\n--------After resort, it becomes:\n";
resortText(text);
displayText(text);
cout<<"\n\nNow please insert some new words:\n";
string new_word;
while(cin>>new_word)
{
vector<string>::iterator location=insertLocation(new_word, text);
text.insert(location,1,new_word);
cout<<"\n--------After you have added the new words, the original text has changed into(sorted in the dictionary order):\n";
displayText(text);
}
cin.clear();
}
void resortText(vector<string> &text)
{
vector<string>::iterator beg=text.begin(), end=text.end(),index1=beg,index2=index1;
for(;index1 != end; ++index1)
{
for(index2 = index1+1; index2 != end; ++index2)
{
if(*index1 > *index2)
{
string temp = *index1;
*index1 = *index2;
*index2=temp;
}
}
}
}
vector<string>::iterator insertLocation(string word, vector<string> text)
{
vector<string>::iterator location=text.begin();
while((location != text.end()) && word>*location)
{
++location;
}
return location;
}