标记字符串并构建multimap
tokenise a string and building a multimap
我有一个像下面这样的字符串:
"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
相关文章:
- 使用std::multimap迭代器创建std::list
- C++为构建时间获取QDateTime的可靠方法
- 无法在 CLion 中构建 C++ 项目
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用ndk-build.cmd构建Android.so文件
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 构建一个由C和C++文件组成的库
- llvm构建器向基本块添加终止符
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- 如何跨平台将二进制资源构建到程序中?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 如何解决 Ninja c++ 构建和执行问题
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- CMake WxWidgets项目成功地在Linux上构建,但没有在Windows上构建
- 更改命令行 qt5 源代码构建配置的正确/快速方法
- 标记字符串并构建multimap