1

if声明看起来太尴尬了,因为我需要增加常量数量的可能性。很抱歉用那个“常数”而不是我的意思来误导你。

4

5 回答 5

9

将所有常量添加到 std::set 然后您可以检查该集合是否包含您的字符串

std::set<std::string> myLookup;
//populate the set with your strings here

set<std::string>::size_type i;

i = myLookup.count(searchTerm);
if( i )
    std::cout << "Found";
else 
    std::cout << "Not found";
于 2009-08-21T11:12:10.437 回答
3

取决于你是否关心性能。

如果不是,那么最简单的代码可能是将各种字符串放入一个数组(或向量,如果您的意思是要在运行时增加常量的数量)。对于少量字符串,这也将非常快:

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 将通过集合的初始化列表来改进事情。

于 2009-08-21T11:16:39.133 回答
2

将要比较的字符串放在静态向量或集合中,然后使用 std::find 算法。

于 2009-08-21T11:11:11.560 回答
1

技术上最好的解决方案是:为您的字符串常量集构建一个“完美的散列函数”,这样以后在散列过程中就不会发生冲突。

于 2009-08-21T11:45:15.657 回答
0
const char * values[]= { "foo", "bar", ..., 0 };

bool IsValue( const std::string & s ) {
   int i = 0;
   while( values[i] ) {
      if ( s == values[i] ) {
         return true;
      }
      i++;
   }
   return false;
}

或者使用 std::set。

于 2009-08-21T11:13:58.093 回答