I have a vector which contains several pairs(INT,INT). I want to search for a particular but I only have one key of that pair. How should I search for the second key?
Asked
Active
Viewed 1,205 times
0
-
[`std::find_if`](http://en.cppreference.com/w/cpp/algorithm/find) should work for such a search. – R Sahu Jun 07 '17 at 05:32
-
1https://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element – Sumit Kumar Jun 07 '17 at 06:06
-
1Possible duplicate of [find\_if and std::pair, but just one element](https://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element) – luk32 Jun 07 '17 at 11:06
1 Answers
0
You can use the following algorithm (pseudo code):
let vec be the input vector
let key be the value that you are searching
for each pair p in vec
let p_1 be p.first
if p_1 == key
return you have found the key
Here is a functional approach to extract re-usable components:
find_if(beg, end, predicate):
let beg be an iterator to the beginning of a sequence
let end be an iterator to the end of a sequence
let predicate be a function from container element to boolean
for each iterator in beg...end
let element be what the iterator points to
if predicate(element)
return iterator
Now, you can define a custom predicate function:
my_predicate(p):
let p be a pair
let p_1 be p.first
let key be the value that you are searching
return p_1 == key
And use find_if:
let vec be the input vector
found_iterator = find_if(begin(vec), end(vec), my_predicate)
It just so happens that the C++ standard library contains std::find_if
with pretty much identical interface to my pseudo code.

eerorika
- 232,697
- 12
- 197
- 326