【问题标题】:Use the std::find() to search a vector of user defined structures [duplicate]使用 std::find() 搜索用户定义结构的向量 [重复]
【发布时间】:2013-08-25 15:57:59
【问题描述】:

以下开始后:

#include <vector>
#include <algorithm>

struct OBJECT{
        char VALUE;
        int COUNTER;
}
vector <OBJECT> MyCollection;   
vector <OBJECT> ::iterator begin,end;
char TEMP;

begin=MyCollection.begin();
end=MyCollection.end();

...我想使用 Find() 函数来搜索向量中 OBJECT 条目的 VALUE 字段,例如:

find (begin, end, TEMP);

(稍后成功对找到的 OBJECT 执行 COUNTER++)。

默认情况下这是不可能的,因为 TEMP 不是 OBJECT 类型而是一个字符。

有什么想法吗?

作为一名学生,我无法将建议转换为工作代码,因此围绕 .at() 方法编写了自己的解决方案并删除了迭代器 begin 和 end。

int MyCollectionIterator=MyCollection.size(); 

while(1){
  if(MyCollectionIterator){ 
    if( MyCollection.at(--MyCollectionIterator).VALUE==TEMP ){
          MyCollection[MyCollectionIterator].COUNTER++; 
          break;
    }
  }else break;
} 

【问题讨论】:

标签: c++ vector


【解决方案1】:

你想使用std::find_if 这样的东西:

struct is_equal {
    char target_;
    isEqual(char target) : target_(target) {};
    bool operator () (const OBJECT& obj) {
        return obj.VALUE == target_;
    };
};
char target_char = // set this to the character you're looking for
vector<OBJECT>::iterator it = std::find_if(begin, end, is_equal(target_char));
if (it != end) {
    it->COUNTER++;
}

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 2010-10-10
    • 2020-03-29
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    相关资源
    最近更新 更多