如何检查字符串是否在字符串数组中

新手上路,请多包涵
#include <iostream>
#include <string>
using namespace std;

bool in_array(string value, string *array)
{
    int size = (*array).size();
    for (int i = 0; i < size; i++)
    {
        if (value == array[i])
        {
            return true;
        }
    }

    return false;
}

int main() {
    string tab[2] = {"sdasd", "sdsdasd"};
    string n;
    cin >> n;
    if (in_array(n, tab)) {

    }
    return 0;
}

如果 n 字符串在 选项卡 数组中,我想检查 C++,但代码返回错误。我做错了什么?也许我应该使用向量?

原文由 user3050705 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
1 个回答
int size = (*array).size();

它不会告诉您 array 的大小,它会告诉您该数组中第一个字符串的长度,您应该将数组的长度分别传递给函数。该函数应如下所示:

 bool in_array(string value, string *array, int length)

但更好的选择是使用 std::vectorstd::find

 #include <vector>
#include <algorithm>

bool in_array(const std::string &value, const std::vector<std::string> &array)
{
    return std::find(array.begin(), array.end(), value) != array.end();
}

然后,您可以像这样使用它:

 std::vector<std::string> tab {"sdasd", "sdsdasd"};

if (in_array(n, tab))
{
    ...
}

原文由 masoud 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题