这可能听起来像一个基本问题,它肯定是可以解决的,但我正在寻找一个快速和优雅的解决方案.
我想为我的程序创建一个保留字的集合:
{"apple", "orange", "peach"}
它是常量,我希望能够在运行时检查字符串s是否为保留字(f s是集合的一部分).
我考虑过使用std::set但我不想手动将每个保留字添加到集合中.此外,我不需要set的全部功能,例如我不需要添加新元素或删除元素.
这样做的优雅方式是什么?
在现代c ++(c ++ 11)中:
const std::set<std::string> v = { "xyzzy", "plugh", "abracadabra" };
Run Code Online (Sandbox Code Playgroud)
您可以将单词存储在数组中,然后使用std::set范围构造函数:
char const* raw_words[] = { "apple", "orange", "peach" };
std::set<std::string> const words(std::begin(raw_words), std::end(raw_words));
Run Code Online (Sandbox Code Playgroud)
这使用了C++ 11 中的新函数begin和end函数,但您也可以使用指向数组的第一个和一个结束元素的指针在C++ 03中执行此操作.
在C++ 11中,您也可以使用初始化列表来初始化std::set,但并非所有编译器都支持此功能.
还要注意,如果单词集的内容永远不会改变,那么简单地使用sorted std::vector<std::string>with std::lower_bound和std::binary_searchfind元素可能会更好.您可能会发现这会表现得更好.