find in std::vector<std::pair>

Baz picture Baz · Mar 19, 2013 · Viewed 25.6k times · Source

I have a vector of pairs. The first in the pair is of type std::string and the second is of type Container.

What convenient functionality exists in std or boost so that I can return a Container given the string value as key?

UPDATE

It has been commented that I could use a std::map instead, but I actually need to preserve the order of my items, in the order that I push them to the vector.

Answer

Andy Prowl picture Andy Prowl · Mar 19, 2013

A possible solution:

struct comp
{
    comp(std::string const& s) : _s(s) { }

    bool operator () (std::pair<std::string, Container> const& p)
    {
        return (p.first == _s);
    }

    std::string _s;
};

// ...

typedef std::vector<std::pair<std::string, Container> > my_vector;
my_vector v;

// ...

my_vector::iterator i = std::find_if(v.begin(), v.end(), comp("World"));
if (i != v.end())
{
    Container& c = i->second;
}

// ...

Here is a complete example:

#include <vector>
#include <utility>
#include <string>
#include <algorithm>

struct Container
{
    Container(int c) : _c(c) { }
    int _c;
};

struct comp
{
    comp(std::string const& s) : _s(s) { }

    bool operator () (std::pair<std::string, Container> const& p)
    {
        return (p.first == _s);
    }

    std::string _s;
};

#include <iostream>

int main()
{
    typedef std::vector<std::pair<std::string, Container> > my_vector;
    my_vector v;
    v.push_back(std::make_pair("Hello", Container(42)));
    v.push_back(std::make_pair("World", Container(1729)));
    my_vector::iterator i = std::find_if(v.begin(), v.end(), comp("World"));
    if (i != v.end())
    {
        Container& c = i->second;
        std::cout << c._c; // <== Prints 1729
    }
}

And here is a live example.