标记字符串并构建multimap

tokenise a string and building a multimap

本文关键字:构建 multimap 串并 字符串 字符      更新时间:2023-10-16

我有一个像下面这样的字符串:

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

我想对字符串进行标记并将其存储在multimap中,使映射看起来如下:

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

但是我没有任何线索来创建上面的地图。有人能帮忙吗?

这在很大程度上取决于您需要进行多少错误检查。您可以为基于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 << "KeytValuen";
   for(auto n : m)
       std::cout << n.first << "t" << n.second << 'n';
}

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

使用正则表达式:

// $ 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 << "keytvaluen";
  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