3 回答

TA貢獻1830條經(jīng)驗 獲得超3個贊
絕對不如Python優(yōu)雅,但沒有什么比C ++中的Python優(yōu)雅。
您可以使用stringstream...
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代替使用。

TA貢獻2003條經(jīng)驗 獲得超2個贊
使用std :: for_each和lambda可以做一些有趣的事情。
#include <iostream>
#include <sstream>
int main()
{
int array[] = {1,2,3,4};
std::for_each(std::begin(array), std::end(array),
[&std::cout, sep=' '](int x) mutable {
out << sep << x; sep=',';
});
}
請參閱我寫的一堂小課的這個問題。這不會打印結(jié)尾的逗號。同樣,如果我們假設(shè)C ++ 14將繼續(xù)為我們提供基于范圍的等效算法,如下所示:
namespace std {
// I am assuming something like this in the C++14 standard
// I have no idea if this is correct but it should be trivial to write if it does not appear.
template<typename C, typename I>
void copy(C const& container, I outputIter) {copy(begin(container), end(container), outputIter);}
}
using POI = PrefexOutputIterator;
int main()
{
int array[] = {1,2,3,4};
std::copy(array, POI(std::cout, ","));
// ",".join(map(str,array)) // closer
}

TA貢獻1880條經(jīng)驗 獲得超4個贊
另一種選擇是使用std::copy和ostream_iterator類:
#include <iterator> // ostream_iterator
#include <sstream> // ostringstream
#include <algorithm> // copy
std::ostringstream stream;
std::copy(array.begin(), array.end(), std::ostream_iterator<>(stream));
std::string s=stream.str();
s.erase(s.length()-1);
還不如Python好。為此,我創(chuàng)建了一個join函數(shù):
template <class T, class A>
T join(const A &begin, const A &end, const T &t)
{
T result;
for (A it=begin;
it!=end;
it++)
{
if (!result.empty())
result.append(t);
result.append(*it);
}
return result;
}
然后像這樣使用它:
std::string s=join(array.begin(), array.end(), std::string(","));
您可能會問為什么我傳遞了迭代器。好吧,實際上我想反轉(zhuǎn)數(shù)組,所以我這樣使用它:
std::string s=join(array.rbegin(), array.rend(), std::string(","));
理想情況下,我想模板化到可以推斷char類型并使用字符串流的地步,但是我還不能弄清楚。
- 3 回答
- 0 關(guān)注
- 2912 瀏覽
添加回答
舉報