首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于c++的字符串数组令牌分析

基于c++的字符串数组令牌分析
EN

Stack Overflow用户
提问于 2015-11-06 07:44:22
回答 1查看 203关注 0票数 0

两个样本数组:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
if(front_elemnet = "a"){ // find all of the front element with "a"
value_plus(); //plus the value 2+3+4
}

然后检查下一个不同的前端元素。

代码语言:javascript
复制
if(front_elemnet = "b"){ // find all of the front element with "b"
    value_plus(); //plus the value 5+2
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-06 08:46:58

代码语言:javascript
复制
#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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33561801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档