Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a C++ container with a "contains" operation?

I want to use a structure in which I insert integers, and then can ask

if (container.contains(3)) { /**/ }

There has to be something like this.

like image 950
Tim Avatar asked May 31 '11 23:05

Tim


People also ask

What are the three categories of containers?

The three types of containers found in the STL are sequential, associative and unordered.

What is a container in C programming?

A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements.

What does container mean in C++?

A container is an object that stores a collection of elements (i.e. other objects). Each of these containers manages the storage space for their elements and provides access to each element through iterators and/or member functions.

How do you check if a set contains a value C++?

Using find() function The standard solution to check for existence of an element in the set container ( std::set or std::unordered_set ) is to use its member function find() . If the specified element is found, an iterator to the element is returned; otherwise, an iterator to the end of the container is returned.


1 Answers

You can use std::vector.

std::vector<int> myVec;
myVec.push_back(3);
if (std::find(myVec.begin(), myVec.end(), 3) != myVec.end())
{
    // do your stuff
}

You can even make a little helper function:

template <class T>
bool contains(const std::vector<T> &vec, const T &value)
{
    return std::find(vec.begin(), vec.end(), value) != vec.end();
}

Here is how you would use it:

if (contains(myVec, 3)) { /*...*/ }
like image 60
Jesse Emond Avatar answered Oct 02 '22 16:10

Jesse Emond