2015-12-03 160 views

回答

2

這裏有一個選項:

std::ostringstream stream; 
std::copy(aSet.begin(), aSet.end(), std::ostream_iterator<std::string>(stream, ",")); 
std::string result = stream.str(); 
1

accumulate example有代碼來連接整數字符串,它可以很容易地轉換爲你的目的的載體:

std::string s = std::accumulate(std::begin(aSet), 
           std::end(aSet), 
           std::string{}, 
           [](const std::string& a, const std::string &b) { 
            return a.empty() ? b 
              : a + ',' + b; }); 
+0

'O(n2)'複雜性。 – chqrlie

1

這裏有沒有什麼東西可以簡單易讀的方式花式:

string s; 

for (auto const& e : aSet) 
{ 
    s += e; 
    s += ','; 
} 

s.pop_back(); 
+0

對於大集合來說效率極低。 – chqrlie

+0

是的,一如既往地進行分析,如果證明效率低下:優化。可讀性首先。 – emlai

+0

C++編譯器可能能夠優化這種方法的'O(n2)'固有的複雜性,但我對此非常懷疑。 – chqrlie

相關問題