将 vector<int> 转换为字符串

新手上路,请多包涵

我有一个 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 许可协议

阅读 1.6k
2 个回答

绝对不如 Python 优雅,但没有什么比 C++ 中的 Python 更优雅了。

您可以使用 stringstream

 #include <sstream>
//...

std::stringstream ss;
for(size_t i = 0; i < v.size(); ++i)
{
  if(i != 0)
    ss << ",";
  ss << v[i];
}
std::string s = ss.str();

您也可以使用 std::for_each 代替。

原文由 Brian R. Bondy 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题