Search code examples
c++vectorstd-pair

Get a value in a 2D Vector given a key


I have a 2D vector in which i want to use a character key to find a value. For example,

Here is my vector type:

vector<pair<char, double>>

characters: a b c d
double: 1.1 2.1 7.1 1.3

each double coorelates with a character value. I want search the vector for a character and have it give me its corresponding double value. How can I do that using this vector type?


Solution

  • char key = 'a';
    auto find_it = find_if(myvec.begin(), myvec.end(), [key](const pair<char, double>& x) { return x.first == key; });
    double value;
    if (find_it != myvec.end())
    {
        value = find_it->second;
    }