Hate
Hate

Reputation: 1255

Threat only unique strings - what is faster vector<std::string> or just std::string

I read from file some strings, and I need to ignore strings that I already treated. First my thought was to create vector<std::string> where I will store strings and after receiving new one check if it is already in the vector. But then I though that I can do the same using just std::string, I think that it is faster and uses less memory, but this way isn't that obvious then using vector. Which approach is better?

Upvotes: 0

Views: 175

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

A better solution would be to store the strings that you have read in a std::set<string>.

Set lookups are generally faster than lookups in a vector, because sets in C++ standard library are organized as binary trees. If you put all your strings in a single long string, your search would remain linear, and you would have one more problem to solve: dealing with word aliasing. You wouldn't be able to concatenate strings as-is, without a separator, because you wouldn't be able to distinguish between "abc"+"xyz" and "abcxyz"

Upvotes: 2

Related Questions