在std :: vector <std :: pair>中找到

Baz*_*Baz 10 c++ boost std c++98

我有一对矢量.该对中的第一个是std :: string类型,第二个是Container类型.

std或boost中存在哪些方便的功能,以便在给定字符串值作为键的情况下返回Container?

UPDATE

有人评论说我可以使用std :: map,但实际上我需要保留我的项目的顺序,按照我将它们推送到向量的顺序.

And*_*owl 7

可能的解决方案:

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;
}

// ...
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子:

#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
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个实例.