我在迭代时可以从std :: list中删除元素吗?例如:
std::list<int> lst;
//....
for (std::list<int> itr = lst.begin(); itr != lst.end(); itr++)
{
if (*itr > 10)
lst.remove(*itr);
}
Run Code Online (Sandbox Code Playgroud)
?为什么?
我有一个字符串的源容器我想从源容器中删除与谓词匹配的任何字符串,并将它们添加到目标容器中.
remove_copy_if
和其他算法只能重新排序容器中的元素,因此必须由erase
成员函数跟进.我的书(Josuttis)说remove_copy_if
在目标容器中的最后一个位置之后返回一个迭代器.因此,如果我只在目标容器中有一个迭代器,我erase
该如何调用源容器?我已经尝试使用目标的大小来确定从源容器的末尾回去多远,但没有运气.我只提出了以下代码,但它会进行两次调用(remove_if
和remove_copy_if
).
有人能让我知道正确的方法吗?我确信两次线性调用不是这样做的方法.
#include <iostream>
#include <iterator>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
class CPred : public unary_function<string, bool>
{
public:
CPred(const string& arString)
:mString(arString)
{
}
bool operator()(const string& arString) const
{
return (arString.find(mString) == std::string::npos);
}
private:
string mString;
};
int main()
{
vector<string> Strings;
vector<string> Container;
Strings.push_back("123");
Strings.push_back("145");
Strings.push_back("ABC");
Strings.push_back("167");
Strings.push_back("DEF");
cout << "Original list" << endl;
copy(Strings.begin(), Strings.end(),ostream_iterator<string>(cout,"\n"));
CPred Pred("1"); …
Run Code Online (Sandbox Code Playgroud)