c++ - 如何从格式为 "a:b"的字符串数组中填充 C++ 对 vector ?

标签 c++ arrays vector

我如何在 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/

相关文章:

c++ - 将 vector 映射到特定范围

c++ - 如何使用 win32 api 获取域用户帐户列表?

c++ - 如何使用 OpenGL 渲染到多个纹理?

c++ - 在C++中四舍五入

arrays - 加起来等于一个数的组合 - Julia lang

c++ - 使用 Iterator 比较 Vector 中的连续元素

c++ - 奇怪的未声明的变量编译器错误

c++ - 二维点集的压缩 - 想法?

arrays - 如何在 Swift 中将元素追加到全局数组(在 for 循环中)?

c++ - std::vector reserve() 和 push_back() 比 resize() 和数组索引快,为什么?