从地图矢量中删除元素

时间:2010-12-20 21:47:29

标签: c++ stl

我有一张地图矢量:

typedef map<string, string> aMap;
typedef vector<aMap> rVec;
rVec rows;

如何从行中删除某些元素?

以下代码不起作用。

struct remove_it
{
  bool operator() (rVec& rows)
  {
    // Validation code here!

  }
};

rVec::iterator it = remove(rows.begin(), rows.end(), remove_it());
rows.erase(it, rows.end());

我收到了以下错误。

error: no matching function for call to 'remove(std::vector<s
td::map<std::basic_string<char>, std::basic_string<char> > >::iterator, std::vec
tor<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator, mai
n(int, char**)::remove_it)'

感谢。

3 个答案:

答案 0 :(得分:2)

1)首先:请提供一个可编辑的例子 您上面发布的代码存在问题,因为rVec和rowsVector已经互换(如果您发布了实际代码,您可能会看到自己)。

2)您使用了错误的删除。它应该是remove_if

3)仿函数是常数

是正常的

4)operator()应该得到aMap类型的对象(就像你的向量中那样)而不是向量的引用。

5)不要懒惰在标准命名空间中添加对象的std :: 而不是使用using namespace std;

#include <map>
#include <vector>
#include <string>
#include <algorithm>

typedef std::map<std::string, std::string> aMap;
typedef std::vector<aMap>        rVec;

rVec rows;

struct remove_it
{
                 // Corrected type here
  bool operator() (aMap const& row) const  // const here
  {
    // Validation code here!
    return true;
  }
};

int main()
{
                                 // _if herer
    rVec::iterator it = std::remove_if(rows.begin(), rows.end(), remove_it());
    rows.erase(it, rows.end());
}

答案 1 :(得分:1)

remove期望一个值。您正在尝试使用仿函数,您需要使用remove_if

此外,您的仿函数需要接受aMap类型的对象,而不是rVec。

答案 2 :(得分:0)

remove_if是你想要的,而不是remove

相关问题