std::transform, std::back_inserter(), std::string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>

std::string concatter(std::string s1) {
  return s1;
}

int main() {
  std::vector<std::string> vs;
  std::string input, concat;
  while(std::cin >> input)
    vs.push_back(input);
	
  for(int i=0; i < vs.size(); ++i)
    std::cout << vs.at(i) << std::endl;
	
  std::transform(vs.begin(), vs.end(), std::back_inserter(concat), concatter);
	
  std::cout << concat << std::endl;
}


The above code won't compile, and I can't make much sense out of the message the compiler returns. All I know is that the problem lies in the line with std::transform();


transform()
runs the function concatter on all the elements in the range [vs.begin(), vs.end()). Basically, the function takes the current string and returns it. The result of the function (for each element) is stored in in the third argument, which appends that result to concat.

If the input was "I am a newbie", then transform() would begin with "I", concatter() would take that argument and return it, back_inserter() would push it back into concat ... and so on.


Where am I doing wrong?

std::back_inserter uses .push_back() member to insert elements in sequence. concat is a std::string, type of value we operate on is std::string (value contained in vs). And there is no overload std::string::push_back() which accepts std::string
Sorry, but I didn't quite understand.
std::back_inserter(concat) will try to do something like that:
1
2
std::string temp = //...
concat.push_back(temp);
And push_back for std::string expect char as parameter. Not string.
Lets replace that transform with equivalent loop:
1
2
3
4
5
6
auto first1 = vs.begin();
auto last1 = vs.end();
while ( first1 != last1 ) {
  concat.push_back( concatter( *first1 ) ); // error, there is no string::push_back(string)
  ++first1;
}
Ah, now I understand. Thanks a lot.
Topic archived. No new replies allowed.