This might sound like a basic question, and it’s certainly solvable but i’m looking for a quick and elegant solution.
I want to create a collection of reserved words for my program:
{"apple", "orange", "peach"}
It is constant and i want to be able during runtime to check if a string s is a reserved word (f s is part of the set).
I’ve thought about using std::set but i don’t want to add each one of my reserved words to the set manually. Besides, I don’t need the full power of set, for example I don’t need to add new elements or to remove ones.
What is an elegant way of doing it ?
You can store the words in an array, then use the
std::setrange constructor:This makes use of the new
beginandendfunctions in C++11, but you can also do this in C++03 using pointers to the first and one-past-the-end elements of the array.In C++11 you could also use an initializer list to initialize the
std::set, though not all compilers support this feature yet.Note also that if the contents of the set of words never change, it might be better to simply use a sorted
std::vector<std::string>withstd::lower_boundandstd::binary_searchto find elements. You may find that this will perform better.