Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...