c++ - 在 C++ 中按空格拆分字符串的最快方法

标签 c++ string dictionary split

<分区>

我有一个像这样的无序 map :

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

有没有更快的解决方案?

最佳答案

很确定这个问题是题外话。但是我认为你可以做得比这更糟:

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

关于c++ - 在 C++ 中按空格拆分字符串的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27123858/

相关文章:

c++ - 是否可以启动命令行应用程序而不显示其窗口?

c# - 如果我的程序正在将 dll 文件复制到临时目录,我是否需要特定权限?

java - 反转每个奇数字符串并将它们加在一起

javascript - 在 JS 中将字符串的第一行与其余行分开的最佳方法是什么?

python - 将字典列表和变成字典集

python - 排序 OrderedDict 不起作用

c++ - 如何使用 Qt 减少小部件和窗口大小之间的距离?

string - 输出此字符串序列的第 n 遍

c# - 如何序列化从字典派生的类

c++ - 3D 线段和平面相交 - 续