2013-10-10 12 views
0

我有一个2D矢量,我想用字符键找到一个值。例如,给定一个键的2D向量中的值

这是我的矢量类型:

vector<pair<char, double>> 

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

用字符值的每个双coorelates。我想要搜索一个角色的矢量,并让它具有相应的双值。我怎样才能使用这种矢量类型?

+2

std :: map会更适合这个。 –

回答

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

更好的数据结构是dictionarymap在CPP。关键是char型,value型有double型;

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; 
相关问题