Find in Vector of a Struct

2019-09-01 06:35发布

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条回答
Fickle 薄情
2楼-- · 2019-09-01 06:52

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.

查看更多
登录 后发表回答