我有一个 vector<int>
具有整数的容器(例如 {1,2,3,4}),我想转换为形式为的字符串
"1,2,3,4"
在 C++ 中最干净的方法是什么?在 Python 中,我会这样做:
>>> array = [1,2,3,4]
>>> ",".join(map(str,array))
'1,2,3,4'
原文由 D R 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用数字库( #include <numeric>
)中的 std::accumulate 解决此问题的另一种方法:
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto comma_fold = [](std::string a, int b) { return std::move(a) + ',' + std::to_string(b); };
std::string s = std::accumulate(std::next(v.begin()), v.end(),
std::to_string(v[0]), // start with first element
comma_fold);
std::cout << s << std::endl; // 1,2,3,4,5,6,7,8,9,10
原文由 hmofrad 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.5k 阅读
3 回答485 阅读✓ 已解决
绝对不如 Python 优雅,但没有什么比 C++ 中的 Python 更优雅了。
您可以使用
stringstream
…您也可以使用
std::for_each
代替。