在网上搜索了很多,但找不到问题的答案。
我正在使用它的 reverse_iterator 向 std::list 插入一个值。虽然插入按预期发生在适当的位置,但我注意到用于插入的原始 reverse_iterator 的值发生了变化。完全不相关的 reverse_iterator 的值也会发生变化。我已经能够在一个简单的例子中重现这个
#include <iostream>
#include <list>
#include <string>
int main()
{
// Creating a list of values 1, 2, 4, 5
std::list<int> myList;
myList.push_back(1);
myList.push_back(2);
myList.push_back(4);
myList.push_back(5);
// Changing it to 1, 2, 3, 4, 5 by inserting 3
std::list<int>::reverse_iterator revIter = myList.rbegin();
while(2 != *revIter)
{
std::cout << *revIter << "\t";
++revIter;
}
std::cout << "\n" << "Reverse iterator now points to " << *revIter;
// Creating a copy of the reverse Iter before inserting.
std::list<int>::reverse_iterator newRevIter = revIter;
myList.insert(revIter.base(), 3);
// Checking the values of revIter and newRevIter
std::cout << "\n" << "Reverse Iterator now points to " << *revIter; // UNEXPECTED RESULT HERE
std::cout << "\n" << "New Reverse Iterator now points to " << *newRevIter; // UNEXPRECTED RESULT HERE
std::cout << "\n" << "Printing final list:" << "\n";
for(std::list<int>::iterator iter = myList.begin(); myList.end() != iter; ++iter)
{
std::cout << *iter << "\t"; // Results are fine
}
return 0;
}
结果
5 4
Reverse iterator now points to 2
Reverse iterator now points to 3
New Reverse iterator now points to 3
Printing final list:
1 2 3 4 5
这是预期的行为。如果是这样,如何使用反向迭代器将项目插入列表(或者在这方面它没用)?