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!
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