Fihop
Fihop

Reputation: 3177

how to use find algorithm for a vector

If the vector's element is a pair type, like vector<pair<int, double>>. I want to the find algorithm focus on the first element of my vector. How can I do this?

For example, the following is my data:

<1, 2>

<3, 5>

<3, 4>
...

I want the find 1 in the first column.

Thanks,

Upvotes: 4

Views: 2081

Answers (4)

MerickOWA
MerickOWA

Reputation: 7602

If you're using newer C++ compiler you could write

int value_to_find = 1;
auto it = find_if( v.begin(), v.end(), [=]( const pair<int,double> &p ) { return p.first == value_to_find; } );
if ( it != v.end() ) {
    // found!
    }

Upvotes: 2

sehe
sehe

Reputation: 393064

Going out of my way to make the answer generic:

template <typename K>
struct match_first
{
    const K _k; match_first(const K& k) : _k(k) {}
    template <typename V>
        bool operator()(const std::pair<K, V>& el) const 
    {
        return _k == el.first;
    }
};

use it like, e.g.

it = std::find_if(vec.begin(), vec.begin(), match_first<int>(1));

if (it!=vec.end())
{ 
    // found
}

Upvotes: 4

Sani Huttunen
Sani Huttunen

Reputation: 24385

Regardless of language/platform this is what you need to do (in pseudo code):

min = MAXIMUM_INTEGER_VALUE
minValue = 0
for each (element in vector)
  if (element.key < min)
    min = element.key
    minValue = element.value
  end if
loop for

Now you should have the smallest key and it's value in min and minValue respectively.
However you COULD in the extreme case of when all keys are equal to MAXIMUM_INTEGER_VALUE end up with the wrong result. The solution would be to assign the first elements value to minValue instead of 0 during initialization.

Upvotes: 0

Dan D.
Dan D.

Reputation: 74655

why not use a multimap<int, double> instead of a vector? its .find(1) would yield an iterator that would give the pair pair<int, double>(1,2) as in your example; http://www.sgi.com/tech/stl/Multimap.html

Upvotes: 1

Related Questions