0

I have a simple function in C++ that checks whether a given element exists in a given array and return true or false accordingly. Here is an example of the code and how I am trying to use it:

#include <iostream>

using namespace std;

bool find_elem(string array[], string elem)
{
    return (find(begin(array), end(array), elem) != end(array));
}

int main(void)
{
    string names[] = {"Bob", "Bill", "Sally", "Mark"}

    if (find_elem(names, "Bob))
    {
        cout << "Bob is in the array" << endl;
    }
    else
    {
        cout << "Bob is not in the array" << endl;
    }
    
    return 0;
}

I am getting an error message on the return statement for the find_elem() function saying clang++: error - no matching function for call to 'begin' as well as two more that say the same for end. I am not sure why this is happening because this line of code works just fine in the main() function of my program, but if I try to use it anywhere else, it returns an error. Can somebody explain why this is happening and how I might fix it? I only recently started learning C++ so examples or suggestions for how to do this better would be more than welcome.

Shock9616
  • 116
  • 9
  • What is `order`? – Lukas-T Dec 16 '20 at 21:37
  • Oh whoops. Order is the wrong name. It is supposed to be array. I will change that – Shock9616 Dec 16 '20 at 21:39
  • @UnholySheep I think it answers the "why" part of my question, but not the "how do I fix it" part. using the `by_pointer` method, I get new errors saying `unknown type name 'T'` and `use of undeclared identifier 'U'`. I don't really understand what these are so a better explaination would be helpful – Shock9616 Dec 16 '20 at 21:45
  • `T` is supposed to be replaced with a type (in your case `string`) and `U` has to be a compile-time constant (in your case 4) - the latter is explained in the answer – UnholySheep Dec 16 '20 at 21:47
  • Another question that might be relevant is: https://stackoverflow.com/questions/5724171/passing-an-array-by-reference – UnholySheep Dec 16 '20 at 21:49
  • Use a `std::vector` instead of an array, and things will work much better. Also, you need to `#include ` to use `std::find()` as well as `#include ` for `std::string`. – Fred Larson Dec 16 '20 at 21:54

0 Answers0