Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;将字符串与字符串数组进行比较_C++_Arrays - Fatal编程技术网

C++ C++;将字符串与字符串数组进行比较

C++ C++;将字符串与字符串数组进行比较,c++,arrays,C++,Arrays,如果我有: const string food[] = {"Burgers", "3", "Fries", "Milkshake"} string word; cin >> word; 我如何将单词与正确的食物进行比较?或者更确切地说,如果用户输入“Fries”,我如何将其与字符串数组进行比较?与find: #include <algorithm> #include <iterator> auto it = std::find(std::begin(foo

如果我有:

const string food[] = {"Burgers", "3", "Fries", "Milkshake"}
string word;
cin >> word;

我如何将单词与正确的食物进行比较?或者更确切地说,如果用户输入“Fries”,我如何将其与字符串数组进行比较?

find

#include <algorithm>
#include <iterator>

auto it = std::find(std::begin(food), std::end(food), word);

if (it != std::end(food))
{
    // found *it
}
else
{
    // not found
}
#包括
#包括
自动it=std::find(std::begin(食物)、std::end(食物)、word);
如果(它!=标准::结束(食物))
{
//找到了
}
其他的
{
//找不到
}

使用
中查找算法:

或使用循环:

for (const auto &item : food) {
    if (item == word) {
        // found it
    }
}

尽管如此,如果您需要经常这样做,最好将项目存储在为快速搜索而设计的数据结构中:
std::set
std::unordered_set

,这是正确的。如果用户输入“Fries”,我会试图找出如何将food[]与WordArray进行比较。数组似乎是错误的结构。我会将数据存储在
std::map
中,以利用查找功能。@andre:a
std::set
似乎更合适。我很好奇这个问题是否会把所有的男孩都带到院子里来。。。
for (const auto &item : food) {
    if (item == word) {
        // found it
    }
}