Here is my single parse code for splitting a std::string
on a char
into a std::vector<std::string>
:
#include <iostream>
#include <vector>
std::vector<std::string> split_uri(std::string, unsigned chr='/');
int main() {
std::vector<std::string> uri_v = split_uri(uri, '/');
for (auto elem: uri_v)
std::cout << elem << std::endl;
}
std::vector<std::string> split_uri(std::string uri, unsigned chr) {
bool start=true;
std::string part;
std::vector<std::string> vec;
vec.reserve(uri.length()/2);
for(char c: uri) {
switch(c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
part += c;
break;
default:
if (c == chr) {
if (!start)
vec.push_back(part);
else start = false;
part.clear();
part += c;
}
else {
std::cerr << "Invalid URI; from: \'" << c << "\' (hex: " << std::hex << "0x" << (unsigned int)c << ")\n";
vec.clear();
return vec;
}
}
}
return vec;
}
What can I do to improve its efficiency?
case chr:
won't work sincechr
is not a constant expression. – Morwenn Apr 4 at 8:58constexpr
for that. – A T Apr 4 at 8:58case
only accepts integer and char literals, not generalized constant expressions. – Morwenn Apr 4 at 8:59constexpr
and aswitch
/case
. – A T Apr 4 at 9:02