2015-11-06 44 views
0

两个样本阵列:字符串数组使用令牌分析C++

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|ba is front_element b is 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 
    } 
+1

我有n o想出你的问题是什么。请参阅[我如何提出一个好问题?](http://stackoverflow.com/help/how-to-ask) –

+0

您可以更改数据的存储方式吗?将数据添加到数组时,您可以为每个字母保留一个计数吗?还是提供完整的?钥匙总是一封信吗? –

+0

你是否需要*使用数组?你不能使用例如地图? –

回答

0
#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/

+0

thx给予方向 –