如果我有:
const string food[] = {"Burgers", "3", "Fries", "Milkshake"}
string word;
cin >> word;如何将单词与正确的食物进行比较?或者更确切地说,如果用户输入"Fries",我如何将其与字符串数组进行比较?
发布于 2013-09-11 21:36:29
使用来自<algorithm>的find算法
auto found = std::find(std::begin(food), std::end(food), word);
if (found == std::end(food)) {
// not found
} else {
// found points to the array element
}或者使用循环:
for (const auto &item : food) {
if (item == word) {
// found it
}
}不过,如果您经常需要这样做,最好将这些项存储在一个专为快速搜索而设计的数据结构中:std::set或std::unordered_set。
https://stackoverflow.com/questions/18742637
复制相似问题