1

I have an unordered map like this:

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

I also have string like this

std::string text = "This is really long text. Sup?";

I'm looking for the fastest solution to split the text string by space and add each word to the unordered map without using third-party libraries. I'll only split it by space, so I'm not looking for solution with changeable delimiter.

I figured out this solution:

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

Are there any faster solutions?

Jongware
  • 22,200
  • 8
  • 54
  • 100
Deepsy
  • 3,769
  • 7
  • 39
  • 71

1 Answers1

1

I think you could do worse than this:

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

Output:

split: en
string: en
to: en
is: en
the: en
this: en
Dharman
  • 30,962
  • 25
  • 85
  • 135
Galik
  • 47,303
  • 4
  • 80
  • 117