相关疑难解决方法(0)

remove_if等效于std :: map

我试图根据特定情况从地图中删除一系列元素.我如何使用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)

c++ stl map

113
推荐指数
5
解决办法
5万
查看次数

在只读结构中分配数据成员,在STL集中分配类

我遇到的问题的最小例子如下:

#include <set>
using namespace std;

class foo {
public:
  int value, x;
  foo(const int & in_v) {
   value = in_v;
   x = 0;
  }
  bool operator<(const foo & rhs) const {
   return value < rhs.value; 
 }
};

int main() {
  foo y(3);
  set<foo> F;
  F.insert(y);

  // Now try to modify a member of the set
  F.begin()->x=1;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

随着错误error: assignment of data-member ‘foo::value’ in read-only structure.我觉得我在这里缺少一些简单的东西,但为什么我无法修改x班上的成员?

c++ stl

9
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×2

stl ×2

map ×1