首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

vector中的插入和排序,出了异常,不知道什么原因

2013-10-25 
vector中的插入和排序,出了错误,不知道什么原因本帖最后由 u011873969 于 2013-10-23 03:47:03 编辑#inclu

vector中的插入和排序,出了错误,不知道什么原因
本帖最后由 u011873969 于 2013-10-23 03:47:03 编辑 #include部分我就不写了。
这个程序要做的事情很简单:
首先输入一些单词组成的文章text,
然后将这文章中的所有单词按照字典顺序排序,
然后输出排序的结果,
然后电脑问用户是不是需要添加一些单词
然后用户输入任意多的单词,每输入一个,程序都会用按照字典顺序将其插入到text中,并输出排序的结果。

编译的时候没问题,但是运行的时候,到了while语句部分时,就会弹出窗口报错,说vector iterators incompatible,无法理解,自认为不会有这样的错误。哪位大神来解释一下子呢?

注:displayText是把一个vector<string>类型的变量中的所有元素输出的函数



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;
}
iterator vector
[解决办法]
应该是因为不用引用,传递的是vector的拷贝,造成了返回的迭代器和原来的vector位置不匹配。

详细的说就是值传递会造成一个临时拷贝,而这个拷贝vector在退出函数时被析构了,跟这个vector有关的迭代器都会失效,但你仍然返回了这个迭代器。

此外,从另一个角度来说也是有问题的,你的insert插入的不是本身的vector迭代器的位置,而是另一个vector的位置,也就是说你想把这个值插入到另一个vector中,而且还是一个无效的vector位置。
[解决办法]
可能说的有点问题,最主要的还是insert插入的时候需要自身的迭代器位置,编译器提示的是迭代器不匹配,就是你指定的迭代器不是自身的
[解决办法]
赞同楼上的,类在离开作用域的时候会自动析构,操作就无效了。用引用传参,传递的是类型本身,操作正确。
[解决办法]
如果没有更改状态,请用const引用

热点排行