C++容器的迭代器失效规则是什么?
优选地以摘要列表格式.
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
下面的代码按预期工作(测试通过)但我想知道如果以这种方式使用迭代器在c ++中被认为是一种不好的做法,或者它是否正常.
也许这是特定的std::vector,其他集合表现不同,最佳实践在集合(甚至他们的实现)之间有所不同?
在其他语言中肯定不行,并且大多数情况下更改集合将使迭代器无效并抛出异常.
BOOST_AUTO_TEST_CASE (ReverseIteratorExample) {
std::vector<int> myvector;
for(int i = 0; i < 5; i++)
{
myvector.push_back(i);
}
// is this generally a bad idea to change the vector while iterating?
// is it okay in this specific case?
myvector.reserve(myvector.size() + myvector.size() - 2 );
myvector.insert(myvector.end(), myvector.rbegin() + 1, myvector.rend() -1);
int resultset [8] = { 0,1,2,3,4,3,2,1 };
std::vector<int> resultVector( resultset, resultset + sizeof(resultset)/sizeof(resultset[0]) );
BOOST_CHECK_EQUAL_COLLECTIONS(myvector.begin(), myvector.end(), resultVector.begin(), resultVector.end());
}
Run Code Online (Sandbox Code Playgroud)
总结问题:
std::vector和其他集合表现不同? …我有以下代码:
//update it in the map
std::map<std::string, std::string>::iterator it;
for(it = spreadsheets.at(i).cells.begin(); it != spreadsheets.at(i).cells.end(); ++it)
{
if(it->first == change.first)
{
if(change.second == "")
{
spreadsheets.at(i).cells.erase(change.first);
}
else
{
it->second = change.second;
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在我的 mac 上完美运行,但是当我在 Linux 计算机上运行时,它会抛出一个 seg 错误spreadsheets.at(i).cells.erase(change.first);
知道是什么导致了这个错误吗?我尝试更改erase(change.first)为erase(it),但仍然出现段错误。
我正在学习如何在我的C++大学课堂中使用向量.我遇到了一个阻碍我使用向量迭代器的问题.这是我的源代码:
template <class T>
void HuffMan<T>::search_freq(T temp) {
//checks for frequency
if(objects.empty()){
objects.push_back(temp);
return;
}
vector<T>::iterator it = objects.begin();
while(it != objects.end()) {
if(*it == temp)
cout<<"added aready\n";
else
objects.push_back(temp);
//this is where the error occurs
//I cannot call 'it++' for some reason
it++;
}
}
Run Code Online (Sandbox Code Playgroud)
此代码始终返回运行时错误,该错误表示"矢量迭代器不可递增".我试图将while循环更改为for循环,但我不认为这与错误的任何事情有关.
信息:我的矢量对象声明如下:
vector<T> objects;
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我指出这个错误吗?
谢谢,Y_Y