There is a wide range of algorithms to find/modify/replace data in containers.
Let's say you have a set of ints, doing what you want is the following:
std::set<int> blah;
// ... some stuff happens ...
if (blah.find(123) != blah.end())
{
// ...
}
Now, you're saying, "but my container doesn't have find!". Not a problem, you can use std::find! std::vector<int> v;
// ... some stuff happens ...
if (std::find(v.begin(), v.end(), 123) != v.end())
{
// ...
}
Note that v can be ANYTHING, as long it supports forward iterators (which all containers do).Now you're saying, "but it's not very efficient! The complexity of find is O(n)!"
True, true. If your container is sorted, you should use binary search O(log n):
if (std::binary_search(v.begin(), v.end(), 123))
{
// ...
}
What's great about this is that it works on any container, provided it's sorted.Then, what you can do is write a metafunction that will call the member function find() when it exists or use std::find() when there's none. This will automatically, and at compile time, use the most efficient way to check for the existence of an entry.