两个样本数组:
string key[] = {"a|b", "a|c","a|d","b|c","b|d"};
int value[]={"2", "3","4","5","2"};这两个数组是连接的<a|b>->2 <a|c>->3 <a|d>->4 <b|c>->5 <b|d>->2。
用"|"分隔的每个键-- front_element和sencond_element的令牌
例如:a|b a是front_element b是second_element
数组可能是一个非常大的数组,我希望找到一种可以快速搜索元素的方法或算法。
if(front_elemnet = "a"){ // find all of the front element with "a"
value_plus(); //plus the value 2+3+4
}然后检查下一个不同的前端元素。
if(front_elemnet = "b"){ // find all of the front element with "b"
value_plus(); //plus the value 5+2
}发布于 2015-11-06 08:46:58
#include <iostream>
#include <map>
#include <string>
using namespace std;
int value_plus(const map<string, int>& myMap, string target)
{
int res = 0;
map<string, int>::const_iterator iter = myMap.begin();
for(; iter!=myMap.end(); ++iter)
{
string key = iter->first;
if(key.substr(0, 1) == target)
{
res += iter->second;
}
}
return res;
}
int main() {
string key[] = {"a|b", "a|c","a|d","b|c","b|d"};
int value[] = {2, 3, 4, 5, 2};
map<string, int> myMap;
for(int i = 0; i < sizeof(key)/sizeof(string); i++)
{
myMap.insert(std::pair<string, int>(key[i], value[i]));
}
cout<<"front_element = a "<<value_plus(myMap, "a")<<endl;
cout<<"front_element = b "<<value_plus(myMap, "b")<<endl;
return 0;
}您可以使用map,请参阅:http://www.cplusplus.com/reference/map/map/
https://stackoverflow.com/questions/33561801
复制相似问题