我如何在 C++ 中填写一个字符串数组中的对 vector ,该字符串遵循具有以下格式的字符串:“a:b”、“c:d”、“e:f” 例如: 字符串 a[] = {"6:7","3:5","5:2"}; 将其转换为 vector> 并且 pair 内容来自 6 和 7,然后是 3 和 5...
我在 boost::lexical_cast 和 strtol 上都没有成功,也许是为了使用正则表达式?还有其他想法吗?
谢谢
最佳答案
最简单的方法可能是使用字符串流来处理转换:
std::pair<int, int> cvt(std::string const &in) {
std::stringstream buff(in);
std::pair<int, int> ret;
buff >> ret.first >> std::ignore(1) >> ret.second;
return ret;
}
如果您的输入可能不是数字,您可以很容易地将它们保存为字符串,例如:
std::pair<std::string, std::string> cvt(std::string const &in) {
std::stringstream buff(in);
std::pair<std::string, std::string> ret;
std::getline(buff, ret.first, ':');
std::getline(buff, ret.second);
return ret;
}
然后您可以使用 std::transform
将其应用于整个输入数组:
std::vector<std::pair<int, int> > pairs; // or std::pair<std::string, std::string>
std::transform(std::begin(a), std::end(a), std::back_inserter(pairs), cvt);
关于c++ - 如何从格式为 "a:b"的字符串数组中填充 C++ 对 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38462743/