Combining a vector of strings

33,845

Solution 1

How about std::copy?

std::ostringstream os;
std::copy( vec_strings.begin(), vec_string.end(), ostream_iterator<string>( os ) );
cout << os.str() << endl;

Solution 2

The following snippet compiles in Visual C++ 2012 and uses a lambda function:

int main () {
    string str = "Hello World!";
    vector<string>  vec (10,str);

    stringstream ss;
    for_each(vec.begin(), vec.end(), [&ss] (const string& s) { cat(ss, s); });

    cout << ss.str() << endl;
}

The accumulate example in the 1st answer is elegant, but as sellibitze pointed out, it reallocates with each concatenation and scales at O(N²). This for_each snippet scales at about O(N). I profiled both solutions with 100K strings; the accumulate example took 23.6 secs, but this for_each snippet took 0.054 sec.

Solution 3

I am not sure about your question.Where lies the problem? Its just a matter of a loop.

#include<vector>
#include<string>
#include<iostream>

int main () 
{
    std::string str = "Hello World!";
    std::vector<string>  vec (10,str);

    for(size_t i=0;i!=vec.size();++i)
        str=str+vec[i];
    std::cout<<str;
}

EDIT :

Use for_each() from <algorithm>

Try this:

#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
string i;
void func(string &k)
{
  i+=k;
}
int main () {
    string str = "Hello World!";
    vector<string>  vec (10,str);

    for_each(vec.begin(),vec.end(),func);
    cout<<i;
    return 0;
  }
Share:
33,845
Bogdan
Author by

Bogdan

Programming is fun and don't forget that.

Updated on May 23, 2021

Comments

  • Bogdan
    Bogdan almost 3 years

    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?