标记化字符串并构建多图

时间:2011-12-08 16:27:50

标签: c++

我的字符串如下:

"1-1-2-1,1-1-3-1,1-2-3-4,2-3-4-5,2-3-5-8"

我希望将字符串标记为字符串并将其存储在多图中,以便地图如下所示:

key    value
1-1     2-1
1-1     3-1
1-2     3-4
2-3     4-5

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

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;
}

但我不知道如上所述创建地图的任何线索。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:4)

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

#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

答案 1 :(得分:3)

使用正则表达式:

// $ 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;
}

实施例

$ 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
相关问题