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

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 is for this.

+3
source share
2 answers

Use std::findfrom <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 do 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);
}
+11
source

Standard library containers are really a way to migrate to C ++.

std :: vector is the default sequence, but you can also use std :: set or others, depending on your use case.

If you don't know which one to use, stick with std :: vector until you have good reason for others.

: http://www.cplusplus.com/reference/vector/vector/begin/

, : http://en.cppreference.com/w/cpp/container/vector

+2

All Articles