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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…