std::string text = "This is really long text. Sup?";
我正在寻找最快的解决方案,以在不使用第三方库的情况下按 space 拆分文本字符串并将每个单词添加到无序映射中。我只会按空格拆分它,所以我不是在寻找具有可变分隔符的解决方案。
我找到了这个解决方案:
void generateMap(std::string const& input_str, std::string const& language) {
std::string buf; // Have a buffer string
std::stringstream ss(input_str); // Insert the string into a stream
while (ss >> buf)
wordsMap.insert({ buf, language });
}
有没有更快的解决方案?
最佳答案
很确定这个问题是题外话。但是我认为你可以做得比这更糟:
int main()
{
const std::string language = "en";
std::string input = "this is the string to split";
std::unordered_map<std::string, std::string> wordsMap;
auto done = input.end();
auto end = input.begin();
decltype(end) pos;
while((pos = std::find_if(end, done, std::not1(std::ptr_fun(isspace)))) != done)
{
end = std::find_if(pos, done, std::ptr_fun(isspace));
wordsMap.emplace(std::string(pos, end), language);
}
for(auto&& p: wordsMap)
std::cout << p.first << ": " << p.second << '\n';
}
输出:
split: en
string: en
to: en
is: en
the: en
this: en