将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'


幕布斯6054654
浏览 497回答 3
3回答

繁花如伊

绝对不如Python优雅,但没有什么比C ++中的Python优雅。您可以使用stringstream...std::stringstream ss;for(size_t i = 0; i < v.size(); ++i){&nbsp; if(i != 0)&nbsp; &nbsp; ss << ",";&nbsp; ss << v[i];}std::string s = ss.str();您也可以std::for_each代替使用。

偶然的你

使用std :: for_each和lambda可以做一些有趣的事情。#include <iostream>#include <sstream>int main(){&nbsp; &nbsp; &nbsp;int&nbsp; array[] = {1,2,3,4};&nbsp; &nbsp; &nbsp;std::for_each(std::begin(array), std::end(array),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[&std::cout, sep=' '](int x) mutable {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;out << sep << x; sep=',';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;});}请参阅我写的一堂小课的这个问题。这不会打印结尾的逗号。同样,如果我们假设C ++ 14将继续为我们提供基于范围的等效算法,如下所示:namespace std {&nbsp; &nbsp;// I am assuming something like this in the C++14 standard&nbsp; &nbsp;// I have no idea if this is correct but it should be trivial to write if it&nbsp; does not appear.&nbsp; &nbsp;template<typename C, typename I>&nbsp; &nbsp;void copy(C const& container, I outputIter) {copy(begin(container), end(container), outputIter);}}using POI = PrefexOutputIterator;&nbsp; &nbsp;int main(){&nbsp; &nbsp; &nbsp;int&nbsp; array[] = {1,2,3,4};&nbsp; &nbsp; &nbsp;std::copy(array, POI(std::cout, ","));&nbsp; // ",".join(map(str,array))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// closer}

侃侃无极

另一种选择是使用std::copy和ostream_iterator类:#include <iterator>&nbsp; // ostream_iterator#include <sstream>&nbsp; &nbsp;// ostringstream#include <algorithm> // copystd::ostringstream stream;std::copy(array.begin(), array.end(), std::ostream_iterator<>(stream));std::string s=stream.str();s.erase(s.length()-1);还不如Python好。为此,我创建了一个join函数:template <class T, class A>T join(const A &begin, const A &end, const T &t){&nbsp; T result;&nbsp; for (A it=begin;&nbsp; &nbsp; &nbsp; &nbsp;it!=end;&nbsp; &nbsp; &nbsp; &nbsp;it++)&nbsp; {&nbsp; &nbsp; if (!result.empty())&nbsp; &nbsp; &nbsp; result.append(t);&nbsp; &nbsp; result.append(*it);&nbsp; }&nbsp; return result;}然后像这样使用它:std::string s=join(array.begin(), array.end(), std::string(","));您可能会问为什么我传递了迭代器。好吧,实际上我想反转数组,所以我这样使用它:std::string s=join(array.rbegin(), array.rend(), std::string(","));理想情况下,我想模板化到可以推断char类型并使用字符串流的地步,但是我还不能弄清楚。
打开App,查看更多内容
随时随地看视频慕课网APP