One of the highest voted questions under the c++ tag is called "Splitting a string in C++". In it, the questioner asks: "What's the most elegant way to split a string in C++?".
The highest voted answer to this question provides these two functions:
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;
return split(s, delim, elems);
}
These functions work great. But I am trying to understand why the answerer didn't combine these two functions into one function. Is there some performance, usability or readability benefit that I am not seeing that you miss out on when you combine these functions? Full program with combined function is below:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
// splitting them into two seperate functions is unnecessary it seems to me, and makes the underlying function harder to understand.
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;
}
int main()
{
std::vector<std::string> x = split("one:two::three", ':');
for (int i = 0; i<x.size(); ++i) cout << x[i] << '\n';
return 0;
}
I find this function split apart to be exceedingly less elegant - and harder to understand - but I feel like I must be missing something. Why didn't he just combine them?