2013-01-11 70 views
1

我正在學習C++,並想知道做下列事情的最好或最習慣的方法是什麼。我有一個已知的字符串列表,這些字符串對於一個程序來說是不變的。我想知道提供給函數的字符串是否在我接受的字符串列表中。我想出了:如何在字符串列表中找到匹配的字符串

bool match(const char* foo, const char* bar) { 
    return strcmp(foo, bar) == 0; 
} 

bool thingIsValid(const char* thing) { 
    return match("foo", thing) || match("bar", thing) || match("baz", thing); 
} 

... 
thingIsValid(someArg.c_str()); 
... 

這種方法似乎更多的是我的C語言習慣。在其他語言中,我可能只是列表並在該列表上做一個.contains(事物)。人們通常在C++中如何做到這一點?

+1

使用'std :: string'和'std :: find'。什麼是指針? –

回答

6

也許這些天的最佳方法是使用一個無序集:

std::unordered_set<std::string> ValidValues {"one", "two", "three"}; 

if(ValidValues.find(testString) == ValidValues.end()) { 
    // String is not valid... 
} 

這裏唯一真正的缺點是,你不能簡單地鋪陳在你的可執行映像的有效字符串。 (設置這個集合需要初始化代碼和堆分配。)但是這對絕大多數應用程序來說應該沒有關係。

+0

如果您還沒有使用C++ 11,只需使用std :: set 。 – phonetagger

+0

使用count而不是find可讀性更強一些:'if(ValidValues.count(testString)){/ * valid * /} else {/ * not valid * /}'。你可能也想看看正則表達式。 – lego

2

一種可能的方式做到這一點:

bool thingIsValid(const std::string &thing) { 
    static const std::vector<std::string> validValues {"foo", "bar", "baz"}; 
    return std::find(validValues.begin(), validValues.end(), thing) != validValues.end(); 
} 

上面片的代碼使用C++ 11列表初始化來創建vector。如果您沒有C++ 11,則必須使用push_back()來構建該向量。

相關問題