How to check if string is in array of strings

arrays, c++, string

Solution

int size = (*array).size();

It will not tell you the size of `array`, it tells you the length of first string in that array, you should pass the length of array to the function separately. The function should look like:

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

But a better choice is using `std::vector` and `std::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();
}

and then, you can use it like:

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

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

Problem

``` #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; } ``` I want to check in C++ if n string is in tab array, but the code return an error. What I am doing wrong? Maybe I should use the vectors?

Original source

Related problems