I want to implement a simple function that will split std::string
based on the delimiter ,\s
.
For example, split("Emerson, Lake, Palmer")
should yield std::vector<std::string>
of
Emerson
Lake
Palmer
I discovered, that it could be simply achieved with back_inserter()
(the example is very helpful) . The function below iterates over supplied string and copies its content directly to a vector.
std::vector<std::string> split(const std::string& s) {
std::vector<std::string> tokens;
std::string::const_iterator from = s.begin();
for (std::string::const_iterator it = s.begin(); it < s.end(); it++) {
if ( *it == ',' ) {
std::copy(from, it, std::back_inserter(tokens));
from = it + 2;
}
if (it == s.end()-1)
std::copy(from, it+1, std::back_inserter(tokens));
}
return tokens;
}
However, the code doesn't compile with the error
no match for 'operator=' (operand types are 'std::back_insert_iterator<std::vector<std::__cxx11::basic_string<char> > >' and 'const char')
I roughly understand what does it mean, however, I don't know how to go about this. Am I missing something simple to make it work, or the whole concept is not a way to go?