Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c++ - Combining a vector of strings

I've been reading Accelerated C++ and I have to say it's an interesting book.

In chapter 6, I have to use a function from <algorithm> to concatenate from a vector<string> into a single string. I could use accumulate, but it doesn't help because string containers can only push_back characters.

int main () {
  using namespace std;
  string str = "Hello, world!";
  vector<string>  vec (10, str);
  // Concatenate here?

  return 0;
}

How do I join the strings together?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming this is question 6.8, it doesn't say you have to use accumulate - it says use "a library algorithm". However, you can use accumulate:

#include <numeric>
    
int main () {
    std::string str = "Hello World!";
    std::vector<std::string> vec(10,str);
    std::string a = std::accumulate(vec.begin(), vec.end(), std::string(""));
    std::cout << a << std::endl;
}

All that accumulate does is set 'sum' to the third parameter, and then for all of the values 'val' from first parameter to second parameter, do:

sum = sum + val

it then returns 'sum'. Despite the fact that accumulate is declared in <numeric> it will work for anything that implements operator+()


Note: This solution, while elegant, is inefficient, as a new string will be allocated and populated for each element of vec.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...