zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    silverlight的TranslateTransform 的使用
    720 JavaScript函数的this指向
    JavaScript数组
    JavaScriptDOM事件
    JavaScript流程控制语句
    CSS布局案例
    JavaScriptDOM基础
    JavaScriptDOM事件
    JavaScript基础语法
    JavaScript的String对象相关方法
  • 原文地址:https://www.cnblogs.com/westfly/p/3565215.html
Copyright © 2011-2022 走看看