取决于你是否关心性能。
如果不是,那么最简单的代码可能是将各种字符串放入一个数组(或向量,如果您的意思是要在运行时增加常量的数量)。对于少量字符串,这也将非常快:
static const char *const strings[] = { "fee", "fie", "fo", "fum" };
static const int num_strings = sizeof(strings) / sizeof(char*);
然后:
int main() {
const char *search = "foe";
bool match = false;
for (int i = 0; i < num_strings; ++i) {
if (std::strcmp(search, strings[i]) == 0) match = true;
}
}
或者:
struct stringequal {
const char *const lhs;
stringequal(const char *l) : lhs(l) {}
bool operator()(const char *rhs) {
return std::strcmp(lhs, rhs) == 0;
}
};
int main() {
const char *search = "foe";
std::find_if(strings, strings+num_strings, stringequal(search));
}
[警告:我没有测试过上面的代码,我已经把签名弄错了好几次......]
如果您确实关心性能,并且有合理数量的字符串,那么一个快速的选择就是Trie。但这需要付出很多努力,因为标准 C++ 库中没有。您可以使用已排序的数组/向量(使用 std::binary_search 搜索)获得很多好处:
// These strings MUST be in ASCII-alphabetical order. Don't add "foo" to the end!
static const char *const strings[] = { "fee", "fie", "fo", "fum" };
static const int num_strings = sizeof(strings) / sizeof(char*);
bool stringcompare(const char *lhs, const char *rhs) {
return std::strcmp(lhs, rhs) < 0;
}
std::binary_search(strings, strings+num_strings, "foe", stringcompare);
...或使用std::set。但是,除非您在运行时更改字符串集,否则在使用二进制搜索的排序数组上使用集合并没有优势,并且必须用代码填充集合(或向量),而数组可以静态初始化.我认为 C++0x 会改进一些东西,为集合提供初始化列表。