senloa
senloa

Reputation: 311

Statically stored set of strings

I have some string comparison logic in my program, e.g:

std::unordered_set<std::string> relational_operators{
    "==",
    "!=",
    ">",
    "<",
    ">=",
    "<="
};

bool is_relational(std::string token) {
  relational_operators.contains(token);
}

if (is_relational(token)) {
  // ...do stuff
}

All values of set are known at compile time, but checks will be done on user input. How such strings are usually stored in c++? I don't know if storing a set like this is a good idea, probably not because it can possibly throw an error when allocation happens (IDE warnings).

So for example if i had another set of strings (supported operators):

std::unordered_set<std::string> supported_operators {
  // ...
};

Support for new operators will be added over time. So i just want to add a new operator to a set. So basically i want to avoid situation like this:

bool is_supported_op(std::string token) {
  return token == "<" || token == ">" || token == "!="; // ... many more ||
}

Upvotes: 1

Views: 97

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490178

Give that you're apparently not planning to modify the set of strings at run-time, I'd probably use an std::array<std::string, N> to hold them, then use std::binary_search to do the search.

From a theoretical viewpoint, you get O(log N) lookups either way--but in reality, the array is likely to give enough better cache locality to improve performance quite a bit (especially if you're using a modern implementation of std::string that implements the short string optimization).

Upvotes: 4

Related Questions