【问题标题】:How to check if string is in array of strings [duplicate]如何检查字符串是否在字符串数组中[重复]
【发布时间】:2013-11-30 18:11:36
【问题描述】:
#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 字符串在 tab 数组中,我想检查 C++,但代码返回错误。 我做错了什么?也许我应该使用向量?

【问题讨论】:

  • 只需使用std::find。照原样,您假装数组中有五个字符串。
  • (*array).size();array-&gt;size()
  • @H2CO3 (*array).size() 实际上是array[0].size()。看括号
  • @Smac89 我建议您阅读有关指针的初学者 C++ 指南。 (在你不知道自己在做什么之前,不要试图教我 C++。)array[0].size()array-&gt;size() 相同。
  • @H2CO3 感谢您的澄清,但不要回到初学者 c++

标签: c++ arrays string


【解决方案1】:
int size = (*array).size();

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

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

 

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

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

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

int main() {
    std::vector<std::string> tab {"sdasd", "sdsdasd"};
    
    if (in_array(n, tab)) {
        ...
    }
}

【讨论】:

  • +1 用于推荐向量并使用 find 而不是重新发明轮子
  • @user3050705:是的,您需要#include &lt;vector&gt; 并通过--std=c++11 编译器开关(在clang 和gcc 中)启用C++11
【解决方案2】:

当将数组作为参数传递给只接受指针的函数时,您无法在函数内查询数组的大小(因为它已转换为“愚蠢”的指针到第一个元素,仅此而已)。您通常会在签名中添加“count”参数或“end”迭代器。

您要实现的基本上是std::find。它需要两个迭代器(序列的开始和结束)和要找到的元素。只需使用此功能。

std::find(std::begin(tab), std::end(tab), n);

如果找到元素,将返回一个迭代器,否则返回结束迭代器。使用结束迭代器检查是否相等将告诉您是否在数组中找到元素。

如果您不喜欢 std 算法的“迭代器接口”,您可以通过使用模板函数环绕 std::find 来实现类似 PHP 的签名:

template<class Element, class Container>
bool in_array(const Element & element, const Container & container)
{
    return std::find(std::begin(container), std::end(container), element)
            != std::end(container);
}

请注意:此答案假定 C++11。如果您使用较旧的编译器,它可能无法工作,或者只有在编译器标志中添加 -std=c++11 才能工作。

【讨论】:

    【解决方案3】:

    masoud 的答案是正确的,但它过于复杂。你只需要这个。

    bool isInVect=false;
    isInVect = std::find(vector.begin(), vector.end(), stringToFind) != vector.end();
            
    if (isInVect == true)
    {
       cout << "Found string in Vector ..." << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 2021-05-22
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      相关资源
      最近更新 更多