【问题标题】:Fastest way to split a string by space in C++ [duplicate]在 C++ 中按空格分割字符串的最快方法 [重复]
【发布时间】:2014-11-25 10:10:59
【问题描述】:

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

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

有更快的解决方案吗?

【问题讨论】:

    标签: c++ string map split


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2017-11-10
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多