vector 之 find 重载

众所周知,map有find,但vector的find只能调用algorithm中的find通用方法。

参考《How to find an item in a std::vector?

对于结构体来说,如何定义==呢?

想到了重载==操作符,通常的情形是重载相同类型,在例子中,我重载了int类型的。

结果也过了,感觉很请强大,具体参考如下代价

#include <vector>
#include <algorithm>
using namespace std;
struct ReaderInfo {
  int key;
  size_t value;
  bool operator == (const ReaderInfo& other) const {
    return this->key == other.key;
  }
  bool operator == (int key) const {
    return this->key == key;
  }
};
int main()
{
  vector<ReaderInfo> read_map;
  ReaderInfo info;
  for (int i = 0; i < 10; ++i) {
    info.key = i;
    info.value = i;
    read_map.push_back(info);
  }
  for (vector<ReaderInfo>::const_iterator it = read_map.begin();
      it != read_map.end(); ++it) {
    printf("key = %d	 value = %d
", it->key, it->value);
  }
  printf("###########################################
");
  vector<ReaderInfo>::iterator xb = find(read_map.begin(),
      read_map.end(), 2);
  if (xb != read_map.end()) {
    xb->value += 5;
    printf("key = %d	 value = %d
", xb->key, xb->value);
  }
  // 删除key
  read_map.erase(xb);
  for (vector<ReaderInfo>::const_iterator it = read_map.begin();
      it != read_map.end(); ++it) {
    printf("key = %d	 value = %d
", it->key, it->value);
  }
  return 0;
}
View Code
原文地址:https://www.cnblogs.com/westfly/p/3565215.html