Find in Vector of a Struct

萝らか妹 提交于 2019-12-25 08:47:50

问题


I made the following program where there is a struct

struct data
{
   int integers; //input of integers
   int times; //number of times of appearance
}

and there is a vector of this struct

std::vector<data> inputs;

and then I'll get from a file an integer of current_int

std::fstream openFile("input.txt")
int current_int; //current_int is what I want to check if it's in my vector of struct (particularly in inputs.integers)
openFile >> current_int;

and I wanna check if current_int is already stored in my vector inputs. I've tried researching about finding data in a vector and supposedly you use an iterator like this:

it = std::find(inputs.begin(),inputs.end(),current_int)

but will this work if it's in a struct? Please help.


回答1:


There are two variants of find:

  • find() searches for a plain value. In you case you have a vector of data, so the values passed to find() should be data.
  • find_if() takes a predicate, and returns the first position where the predicates returns true.

Using the latter, you can easily match one field of your struct:

auto it = std::find_if(inputs.begin(), inputs.end(), 
                       [current_int] (const data& d) { 
                          return d.integers == current_int; 
                       });

Note that the above uses a C++11 lambda function. Doing this in earlier versions of C++ requires you to create a functor instead.



来源:https://stackoverflow.com/questions/28925349/find-in-vector-of-a-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!