我有一个 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 回答1.3k 阅读✓ 已解决
1 回答1k 阅读✓ 已解决
4 回答832 阅读
1 回答905 阅读
1 回答940 阅读
1 回答707 阅读
1 回答809 阅读
绝对不如 Python 优雅,但没有什么比 C++ 中的 Python 更优雅了。
您可以使用
stringstream
…您也可以使用
std::for_each
代替。