0

文字キーを使用して値を検索したい 2D ベクトルがあります。例えば、

ここに私のベクトルタイプがあります:

vector<pair<char, double>>

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

各 double は文字値と相関します。ベクトルで文字を検索し、対応する double 値を取得します。このベクトル型を使用してそれを行うにはどうすればよいですか?

4

2 に答える 2

1
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;
}
于 2013-10-10T00:57:15.983 に答える
1
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;
}

より良いデータ構造は、cppdictionaryのようなものです。mapキーはchartype であり、valuewith doubletype です。

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;
于 2013-10-10T01:09:39.220 に答える