Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an element exists in a dynamic allocated array C++

Tags:

c++

For example, in Python, I could do:

if 'a' in ['a', 'b', 'c']:
   return 'Hi'

But in C++, I'm not sure what the equivalent function for that is.

like image 821
Kara Avatar asked Jan 23 '26 22:01

Kara


1 Answers

Use std::find from <algorithm>:

std::vector<char> dynamic_array{'a', 'b', 'c'};
auto exists = std::find(dynamic_array.begin(), dynamic_array.end(), 'a')
                  != dynamic_array.end();

You can create a function if you find yourself doing this a lot:

template<typename Container, typename T>
bool contains(Container const& container, T const& value) {
    using std::begin;
    return std::find(begin(container), end(container), value)
               != end(container);
}