我想从 vector 中删除数据,使用它,然后将它重新插入到 vector 中的相同位置。
我将使用它作为“要发送的东西”的缓存,在“发送失败”的情况下重新插入,而新项目具有更高的优先级。只有一个线程会从这个缓存中删除东西,所以不用担心它比最初小,其他线程只能增加它。
我试过这个简单的测试代码,但我发现了一个奇怪的结果,我想了解它发生的原因以及如何解决它:
void printVector(std::vector<int> &vector) {
for (auto i : vector) {
std::cout << i << "\n";
}
std::cout << std::endl;
}
int main() {
std::vector<int> states_cache {1, 2, 3};
printVector(states_cache); // prints: 1 2 3
auto pos = states_cache.end();
int i = states_cache.back();
states_cache.pop_back();
std::cout << "i1: " << i << std::endl;
printVector(states_cache); // prints: 1 2
states_cache.push_back(4);
states_cache.push_back(5);
states_cache.push_back(6);
printVector(states_cache); // prints: 1 2 4 5 6
states_cache.insert(pos - 1, i); // Here I can see at the debugger that pos inner memory structure value changes from 129 to 4, whatever this means
printVector(states_cache); // prints: 33 1 2 4 5 6
}
最后printVector
打印:
33 1 2 4 5 6
我可以在 printVector
看到正在评估的第一项是号码33
, 所以不是数字 3
被打印两次。
我期待它是:
1 2 3 4 5 6
就好像3
被移除、“使用”,然后重新插入到与之前相同的位置。
最佳答案
auto pos = states_cache.end();
此时,pos
不是一个位置,而是一个iterator。到 vector 。
每次您将元素推送到 vector 时, vector 迭代器的末尾 - 您的 pos
当前持有 - 都会失效,因此在这些推送之后 pos
迭代器不再有效但不可用。
如果你想在元素原来所在的位置插入元素,你必须记住被删除元素的索引,然后将该索引转换为 insert
调用的迭代器。
要获取索引,您可以将 std::distance
与两个迭代器一起使用 - 一个是元素,第二个是 vector 的开头。例如,要获取 vector 中最后一个元素的索引,您可以使用
auto ix = std::distance(vec.begin(), vec.end()) - 1;
另请注意,这假定 vector 不为空。
关于c++ - 如何保存 vector 中的位置以供以后插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58140702/