Utility of returning a vector by reference that was passed by reference

c++, pass-by-reference, string, vector

Solution

By returning a reference to the object you passed in you can do some chaining or cascading in one expression and be working with the same vector the whole time. Some people find this conventient: IE

  std::vector<std::string> elems;
  std::cout << "Number of items:" << split("foo.cat.dog", '.', elems).size();

  // get just foo
  std::cout << "First item is:" << split("foo.cat.dog", '.', elems)[0];

  // change first item to bar
  split("foo.cat.dog", '.', elems)[0] = "bar";

Problem

I recently saw the following code-block as a response to this question: Split a string in C++? ``` std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } ``` Why is returning the passed-by-reference array "elems" so important here? Couldn't we make this a void function, or return an integer to indicate success/failure? We are editing the actual array anyway, right? Thank you!

Original source

Related problems