Create a constant set collection of strings c++

c++, stl

Solution

You can store the words in an array, then use the `std::set` range constructor:

char const* raw_words[] = { "apple", "orange", "peach" };

std::set<std::string> const words(std::begin(raw_words), std::end(raw_words));

This makes use of the new `begin` and `end` functions 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>` with `std::lower_bound` and `std::binary_search` to find elements. You may find that this will perform better.

Problem

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 ?

Original source