Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 776
Ben D. Avatar asked Dec 31 '25 01:12

Ben D.


1 Answers

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";
like image 104
Doug T. Avatar answered Jan 02 '26 16:01

Doug T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!