首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >标记字符串并构建多重映射

标记字符串并构建多重映射
EN

Stack Overflow用户
提问于 2011-12-09 00:27:50
回答 2查看 348关注 0票数 0

我有如下字符串:

代码语言:javascript
复制
"1-1-2-1,1-1-3-1,1-2-3-4,2-3-4-5,2-3-5-8"

我希望对字符串进行标记,并将其存储在多映射中,以便映射如下所示:

代码语言:javascript
复制
key    value
1-1     2-1
1-1     3-1
1-2     3-4
2-3     4-5

嗯,我可以使用下面的函数将字符串分割成一个向量

代码语言:javascript
复制
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) 
{
    std::stringstream ss(s+' ');
    std::string item;
    while(std::getline(ss, item, delim)) 
    {
        elems.push_back(item);
    }
    return elems;
}

但我对创建上面的地图一无所知。有人能帮帮忙吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-12-09 00:52:25

这在很大程度上取决于你需要做多少错误检查。您可以将您的逻辑重用于getline()-based循环来解析每一项:

代码语言:javascript
复制
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <stdexcept>
#include <sstream>
int main()
{
   std::multimap<std::string, std::string> m;
   std::string s = "1-1-2-1,1-1-3-1,1-2-3-4,2-3-4-5,2-3-5-8";
   std::stringstream ss(s);
   for(std::string item; std::getline(ss, item, ','); )
   {
       std::stringstream ss2(item);
       std::vector<std::string> tokens;
       for(std::string tok; std::getline(ss2, tok, '-'); )
           tokens.push_back(tok);
       if(tokens.size() != 4)
           throw std::runtime_error("parsing error at item " + item);
       std::string key   = tokens[0] + '-' + tokens[1];
       std::string value = tokens[2] + '-' + tokens[3];
       m.insert(std::make_pair(key, value)); // or m.emplace(key, value);
   }
   std::cout << "Key\tValue\n";
   for(auto n : m)
       std::cout << n.first << "\t" << n.second << '\n';
}

演示:http://ideone.com/zy871

票数 4
EN

Stack Overflow用户

发布于 2011-12-09 01:43:44

使用正则表达式:

代码语言:javascript
复制
// $ g++ -std=c++0x populate-map.cc -o populate-map -lboost_regex
#include <iostream>
#include <map>
#include <string>

#include <boost/regex.hpp> // gcc doesn't fully support c++11 regexs

int main() {
  std::multimap<std::string, std::string> pairs;
  boost::regex re("(\\d-\\d)-(\\d-\\d)"); // key - value pair

  // read lines from stdin; populate map
  for (std::string line; std::getline(std::cin, line); ) {
    boost::sregex_iterator it(line.begin(), line.end(), re), end;
    for ( ; it != end; ++it)
      pairs.insert(std::make_pair((*it)[1].str(), (*it)[2].str()));
  }

  // print map
  std::cout << "key\tvalue\n";
  for (auto v: pairs)
    std::cout << v.first << "\t" << v.second << std::endl;
}

示例

代码语言:javascript
复制
$ echo '1-1-2-1,1-1-3-1,1-2-3-4,2-3-4-5,2-3-5-8' | ./populate-map
key value
1-1 2-1
1-1 3-1
1-2 3-4
2-3 4-5
2-3 5-8
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8434225

复制
相关文章

相似问题

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