我需要浏览一个集合并删除符合预定义条件的元素.
这是我写的测试代码:
#include <set>
#include <algorithm>
void printElement(int value) {
std::cout << value << " ";
}
int main() {
int initNum[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> numbers(initNum, initNum + 10);
// print '0 1 2 3 4 5 6 7 8 9'
std::for_each(numbers.begin(), numbers.end(), printElement);
std::set<int>::iterator it = numbers.begin();
// iterate through the set and erase all even numbers
for (; it != numbers.end(); ++it) {
int n = *it; …Run Code Online (Sandbox Code Playgroud) 我试图根据特定情况从地图中删除一系列元素.我如何使用STL算法?
最初我想使用remove_if但不可能因为remove_if不适用于关联容器.
是否有适用于地图的"remove_if"等效算法?
作为一个简单的选项,我想到循环遍历地图并擦除.但是循环遍历地图并删除安全选项?(因为迭代器在擦除后变为无效)
我使用以下示例:
bool predicate(const std::pair<int,std::string>& x)
{
return x.first > 2;
}
int main(void)
{
std::map<int, std::string> aMap;
aMap[2] = "two";
aMap[3] = "three";
aMap[4] = "four";
aMap[5] = "five";
aMap[6] = "six";
// does not work, an error
// std::remove_if(aMap.begin(), aMap.end(), predicate);
std::map<int, std::string>::iterator iter = aMap.begin();
std::map<int, std::string>::iterator endIter = aMap.end();
for(; iter != endIter; ++iter)
{
if(Some Condition)
{
// is it safe ?
aMap.erase(iter++);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我的代码如下:
unordered_set<AttrValue> output;
...
auto requiredType = variables.at(arg.value);
auto end = remove_if(output.begin(), output.end(),
[&](AttrValue x) {
return !matchingOutputType(requiredType, ast->getNodeType(ast->getNodeKeyAttribute(x)));
}); // queryevaluator_getcandidatelist.cpp(179)
output.erase(end);
Run Code Online (Sandbox Code Playgroud)
错误在代码的第4行.所以我认为这是因为remove_if.但什么是错的?输出没有定义常量?
Error 90 error C3892: '_Next' : you cannot assign to a variable that is const c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm 1840
Error 109 error C3892: '_Next' : you cannot assign to a variable that is const c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm 1840
Run Code Online (Sandbox Code Playgroud)
输出窗口:
3>c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(1840): error C3892: '_Next' …Run Code Online (Sandbox Code Playgroud) 此代码具有Visual Studio error C3892.如果我std::set改为std::vector- 它有效.
std::set<int> a;
a.erase(std::remove_if(a.begin(), a.end(), [](int item)
{
return item == 10;
}), a.end());
Run Code Online (Sandbox Code Playgroud)
怎么了?为什么我不能std::remove_if用std::set?