c++ equivalent of in_array

I'm trying to remake that function as it works in php. I need it to search for a char type from an array of char types. Here's what I have:

char array[][5] = {"1:1","2:2",'\0'}; //an array of 2 with 5 characters per element.

bool in_array(char needle,char haystack[])
{
char arraySize = sizeof(haystack) / sizeof(char);
for(int i = 0; i < arraySize; i++)
{
if(haystack[i] == needle)
{
return true;
}
}
return false;
}

//Goes through the array and if found return true, else reach the end and return false

bool found = in_array("1:1",array);

I've probably made a bunch of mistakes, but I am a right noob when it comes to C++ :x Can somebody put me right? Cheers
Using std::string instead of C-style strings would drastically simplify your function.
As it stands, you are mixing C-style strings with chars.

1
2
3
4
5
6
// Assuming the array size is fixed at compile time (such as your example)
template< size_t N >
bool in_array( const std::string& needle, std::string (&haystack)[ N ] )
{
    return std::find( haystack, haystack + N, needle ) != haystack + N;
}

Last edited on
Topic archived. No new replies allowed.