I would like to use the string splitting function for the highest rated answer to this question:
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?