How to combine elements of a vector in C++

Here is a sample program I am using.

while(split.good()){
            split >>first;
            split >>second;
            word=first + second;
            //cout<< static_cast<char> (word)<<endl;
            vec.push_back(static_cast<char> (word));

        }

first and second are int values. So I want to combine the elements of the vector to make a complete word.

Thanks,


Solution 1:

First and foremost, you should heed @AliciaBytes' advice about your while loop.

To combine all your elements in your vector into a single word, you can use the following std::string constructor that takes two iterators:

template< class InputIt > basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator() );

Pass in a beginning and end iterator of your vector:

const std::string s{std::begin(vec), std::end(vec)};

This will add each element of vec into the std::string. Alternatively, you could use a for loop:

std::string s;
for (auto c : vec)
{
    // Add each character to the string
    s += c;
}