STL - 在 C++ 中,当键是带字符串的结构时,如何在带有仿函数的映射上使用 find_if?

标签 stl dictionary c++

我有一个 STL::map 键类型是自定义结构。我想知道这张 map 是否已经有一个带有特定字符串作为组件的键(在下面标记为“id”),无论它的其他组件的值是什么。灵感来自 this回答和this还有一个,我尝试将 STL::find_if 与自定义 functor 一起使用:

map<myStruct, vector<size_t> > myMap;

struct myStruct
{
  string a, b, c, id;
};

struct checkId : unary_function<pair<myStruct, vector<size_t> >, bool>
{
private:
  string _exp;
public:
  checkId (myStruct x) : _exp(x.id) {}
  bool operator() (const pair<myStruct, vector<size_t> > & p) const
  {
    return p.first.id.compare(_exp) == 0;
  }
};

map<myStruct, vector<size_t> >::iterator it;
myStruct newS;  // to be initialized, but not shown here
it_mP2P = find_if(myMap.begin(), myMap.end(), checkId(newS));

当我编译它时,gcc 返回给我:

/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = myStruct]’:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:347:    instantiated from ‘_Tp& std::map<_Key,_Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = myStruct, _Tp = std::vector<long unsigned int, std::allocator<long unsigned int> >, _Compare = std::less<myStruct>, _Alloc = std::allocator<std::pair<const myStruct, std::vector<long unsigned int, std::allocator<long unsigned int> > > >]’
myprogram.cpp:386:    instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:227:  error: no match for ‘operator<’ in ‘__x < __y’

这是否意味着如果我想使用我的仿函数“checkId”,我必须重载运算符“<”才能使用我的自定义结构?我怎样才能做到这一点?我不是 C++ 专家,所以提前感谢任何一段代码。

最佳答案

http://codepad.org/VYNqdZeF

struct myStruct
{
  std::string a, b, c, id;
  bool operator<(const myStruct& rhs) const //HERES THE MAGIC
  {return id < rhs.id;}                     //WHEEEEEEEEEEEE!
};

这是制作 std::map<myStruct, stuff> 所必需的工作,无需传递自定义比较仿函数。

关于STL - 在 C++ 中,当键是带字符串的结构时,如何在带有仿函数的映射上使用 find_if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8234139/

相关文章:

c++ - 从c++中的函数返回数组 vector

swift - 调用中参数 'dictionary' 缺少参数

python - Python 中的字典分组和聚合列表

c# - ContainsKey(string key) 如何在 Dictionary<string, string> 上抛出 KeyNotFoundException?

c++ - C++中长表达式的优化

CPP 文件中的 C++11 模板定义, undefined reference

c++ - std::max_element() 有多聪明?

c++ - 组类类型

c++ - 需要语法帮助以根据模板参数的类型专门化类方法

c++ - 合并排序算法无法正常工作