1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
template <typename F>
inline void split(const F& function, const char* cstr, const char delim = ' ') {
do {
auto start = cstr;
while (*cstr != delim && *cstr != '\0') ++cstr;
function(start, cstr - start);
} while (*cstr++ != '\0');
}
template <typename F>
inline void split(const F& function, const ::std::string& str, const char delim = ' ') {
split(function, str.c_str(), delim);
}
// VS == std::vector<std::string>
template <typename VS>
inline void split(VS& tokens, const char* cstr, const char delim = ' ') {
size_t num = 0;
split([&tokens, &num] (const char* begin, size_t length) {
if (num < tokens.size()) {
tokens[num].assign(begin, length); //这里进行了tokens的重用,避免clear重新分配内存
} else {
tokens.emplace_back(begin, length); //右值构造,一次赋值
}
++num;
}, cstr, delim);
tokens.resize(num);
}
|