简体   繁体   English

从地图矢量中删除元素

[英]Remove element from vector of maps

I have a vector of maps: 我有一张地图矢量:

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

How can I remove some elements from rows? 如何删除行中的某些元素?

The following code does not work. 以下代码不起作用。

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());

I got the following error. 我收到以下错误。

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)'

Thanks. 谢谢。

1) First off: please provide a single compilable example. 1)首先:请提供一个可编译的示例。
Your code posted above is problematic as rVec and rowsVector have been interchanged (you would have seen that yourself if you had posted real code). 上面发布的代码是有问题的,因为rVec和rowsVector已互换(如果您发布了真实代码,您会发现自己的)。

2) You are using the wrong remove. 2)您使用了错误的删除。 It should be remove_if 应该是remove_if

3) It is normal for the functor to be const 3)函子是常量是正常的

4) The operator() should get object of type aMap (as that is what is in your vector) not a reference back to the vector. 4)operator()应该获取aMap类型的对象(因为这就是您的向量中的内容),而不是对向量的引用。

5) Don't be lazy add std:: in-front of objects in the standard namespace. 5)不要偷懒在标准名称空间的对象前面添加std ::。
rather than using using namespace 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());
}

remove expects a value. remove期望值。 You are trying to use a functor, you need to use remove_if for that. 您正在尝试使用函子,为此需要使用remove_if

Also, your functor needs to accept an object of type aMap, not rVec. 同样,您的函子需要接受aMap类型的对象,而不是rVec类型的对象。

remove_if是您想要的,而不是remove

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM