Accelerated C++ Solution to Exercise 6-9

Exercise 6-9

Use a library algorithm to concatenate all the elements of a vector<string>.

Solution

In Chapter 6, the author introduces the accumulate algorithm which enables easy summation of all numeric elements within a vector<double>.

If you look at section 6.5 (page 121 of the book), the accumulate function takes this form: accumulate(b, e, t), in which arguments b and e defines the asymmetric range [b, e) of the vector elements to be subject for the summation. the argument t represents the initial value of the summation and implies the type the accumulation.

For instance, if we wish to sum all the elements within the vector<double> numbers, with the initial value of 0.0, the summation is computed as accumulate(numbers.begin(), numbers.end(), 0.0).

To concatenate all the elements of a vector<string>, interestingly, we can also leverage this accumulate function.

For instance, if we wish to sum (concatenate) all the elements within the vector<string> words, with the initial value of “” (implies empty vector), the concatenation is computed as accumulate(words.begin(), words.end(), “”). i.e. concatenating all the string elements will give us a giant (longer) string. (It’s an overload!)

Test Program

Fortunately, this concept can be tested out easily by submitting the following very simple main program. One realisation is that the accumulate function is actually under the <numeric> directive, not the <algorithm> directive as I had originally thought.

#include <iostream>    // cout, endl;
#include <vector>      // vector
#include <string>      // string
#include <numeric>     // accumulate

using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::accumulate;

int main () {
    string s = "abc";
    vector<string>  vec (20, s);
    string sentence = accumulate( vec.begin(), vec.end(), string("") );
    cout << sentence << endl;
}

Result

Running the main program confirms that the concatenation can be performed using the accumulate algorithm. i.e. the 20 elements of string “abc” have been concatenated into one giant string element.

abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc

Process returned 0 (0x0)   execution time : 0.394 s
Press any key to continue.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Leave a reply