Question

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?

Était-ce utile?

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

Autres conseils

void find(char a,vector<pair<char,double>> tmpvec){
    for(auto iter = tmpvec.begin();iter != tmpvec.end();iter ++)
        if(iter->first == a){
            cout << iter->second << endl;
                    return;
            }
    cout << "nothing" << endl;
}

The better data struct is dictionary such as map in cpp. The key is char type, and value with double type;

map<char,double> tmpmap;
tmpmap['a'] = 1.1;
tmpmap['b'] = 1.7;
..............
char p;
cin >> p;
if ((auto iter =tmpmap.find(tmpmap.begin(),tmpmap.end()) != tmpmap.end(),p))
    cout << iter->second << endl;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top