【发布时间】:2013-09-26 20:32:13
【问题描述】:
我正在阅读 Josuttis “C++ 标准库,第 2 版。”。在第 6.7.1 节中,作者解释说下面给出的代码会产生意想不到的结果。我仍然不知道std::remove() 的功能,以及为什么我会得到这个奇怪的结果。 (虽然我知道您需要使用std::erase() 才能实际删除元素,实际上最好使用list::erase() 而不是std::remove() 和`std::remove() 的组合)。
list<int> coll;
// insert elements from 6 to 1 and 1 to 6
for (int i=1; i<=6; ++i) {
coll.push_front(i);
coll.push_back(i);
}
// print
copy (coll.cbegin(), coll.cend(), // source
ostream_iterator<int>(cout," ")); // destination
cout << endl;
// remove all elements with value 3
remove (coll.begin(), coll.end(), // range
3); // value
// print (same as above)
结果是
pre: 6 5 4 3 2 1 1 2 3 4 5 6
post: 6 5 4 2 1 1 2 4 5 6 5 6 (???)
【问题讨论】:
-
删除后如何打印?
-
@KarolyHorvath,我刚刚添加了代码!查看打印功能
-
所有值为 3 的元素都被以下元素覆盖。没看到图吗?
-
@newprint 另请注意,在您的情况下,调用
list::remove是far better,而不是使用擦除删除习语。