使用c++进行字符串数组标记分析

String array token analysis using c++

本文关键字:数组 字符串 c++ 使用      更新时间:2023-10-16

两个样本数组:

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是前元素b为第二元素

数组可能是一个非常大的数组,我想找到一种方法或算法可以快速搜索元素

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