文字キーを使用して値を検索したい 2D ベクトルがあります。例えば、
ここに私のベクトルタイプがあります:
vector<pair<char, double>>
characters: a b c d
double: 1.1 2.1 7.1 1.3
各 double は文字値と相関します。ベクトルで文字を検索し、対応する double 値を取得します。このベクトル型を使用してそれを行うにはどうすればよいですか?
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;
}
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
キーはchar
type であり、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;