• 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
  • 相关阅读:
    文件下载断点续传插件webupload插件
    cocos2dx 2.x 粒子渲染时有黑色粒BUG
    VOIP NAT穿越之SIP信令穿越
    hdu 5086 Revenge of Segment Tree(BestCoder Round #16)
    [并发]线程池技术小白
    调用 COM 对象
    switch-case 执行顺序
    HDELETE
    python and java
    部分查询练习题及答案
  • 原文地址:https://www.cnblogs.com/westfly/p/3565215.html
Copyright © 2020-2023  润新知