I would like to use the string splitting function for the highest rated answer to this question:
Split a string in C++?
Copying the answer for convenience:
#include <string>
#include <sstream>
#include <vector>
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;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
I have a question here. Why the declaration is std::vector<std::string> &split(...) rather than void split(...)? As an argument we receive std::vector<std::string> &elems and this is what we want to end up having. Why return anything if we receive a reference?
I have:
int &multA (int &n)
{
n = 5*n;
return n;
}
void multB (int &n)
{
n = 5*n;
}
and:
int n1, n2;
n1 = 1;
n2 = 1;
cout << "n1: " << n1 << endl;
cout << "n2: " << n2 << endl;
n1 = multA(n1);
multB(n2);
cout << "n1: " << n1 << endl;
cout << "n2: " << n2 << endl;
And as a result I have:
n1: 1
n2: 1
n1: 5
n2: 5
What's the difference then?
Returning a reference allows a call to split() to be used as an argument to another function. For example, assume we have some other function that accepts a vector of strings by reference
void func(std::vector<std::string> &elements);
If split() returns a reference, it is possible to pass the reference it returns directly to func().
func(split(s, delim, elems));
whereas, if split() did not return a reference, it would be necessary to do
split(s,delim, elems);
func(elems);
The second usage approach still works if split() returns a reference.
The difference between these two is purely programmer convenience, but a lot of programmers prefer to use the first calling style. Returning a reference is not a particularly expensive operation so allowing the programmer a choice in how to use it does not lose much.
It's syntactic sugar that make the functions more flexible.
By example: you can write
std::cout << "there are " << split(str, delim, vect).size() << " elemements\n";
With the void hypothesis case, you need 2 statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With