在给定键的情况下获取2D矢量中的值

问题描述 投票:0回答:2

我有一个2D矢量,我想在其中使用字符键来查找值。例如,

这是我的矢量类型:

vector<pair<char, double>>

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

每个double与一个字符值相关联。我想搜索一个字符的向量,并让它给我相应的double值。我怎么能用这种矢量类型呢?

c++ vector std-pair
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;
}

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

更好的数据结构是dictionary,例如cpp中的map。关键是char类型,valuedouble类型;

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;
© www.soinside.com 2019 - 2024. All rights reserved.