gpt4 book ai didi

c++ - 不理解 C++ STL 中 std::remove 的结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:15:45 24 4
gpt4 key购买 nike

我正在阅读 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 (???)

最佳答案

explanation应该有帮助:

Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten. Relative order of the elements that remain is preserved and the physical size of the container is unchanged. Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values. A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size.

请注意,std::remove() 的返回值是表示新end 的迭代器。因此,在这个新端和旧端调用 std::erase() 将释放多余的空间。

关于c++ - 不理解 C++ STL 中 std::remove 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19038145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com