在C ++中用空格分割字符串的最快方法

时间:2014-11-25 10:11:00

标签: c++ string map split

我有一个像这样的无序地图:

std::unordered_map<std::string, std::string> wordsMap;

我也有像这样的字符串

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 });
}

有没有更快的解决方案?

1 个答案:

答案 0 :(得分:1)

非常肯定这个问题是偏离主题的。不过,我认为你可以做得更糟:

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
相关问题