Is there a sorted container in the STL?
What I mean is following: I have an std::vector
, where Foo
is a custom made class. I a
I'd like to expand on Jason's answer. I agree to Jason, that either std::set or std::multiset is the best choice for your specific scenario. I'd like to provide an example in order to help you to further narrow down the choice.
Let's assume that you have the following class Foo
:
class Foo {
public:
Foo(int v1, int v2) : val1(v1), val2(v2) {};
bool operator<(const Foo &foo) const { return val2 < foo.val2; }
int val1;
int val2;
};
Here, Foo
overloads the <
operator. This way, you don't need to specify an explicit comparator function. As a result, you can simply use a std::multiset
instead of a std::vector
in the following way. You just have to replace push_back()
by insert()
:
int main()
{
std::multiset ms;
ms.insert(Foo(1, 6));
ms.insert(Foo(1, 5));
ms.insert(Foo(3, 4));
ms.insert(Foo(2, 4));
for (auto const &foo : ms)
std::cout << foo.val1 << " " << foo.val2 << std::endl;
return 0;
}
Output:
3 4
2 4
1 5
1 6
As you can see, the container is sorted by the member val2
of the class Foo
, based on the <
operator. However, if you use std::set
instead of a std::multiset
, then you will get a different output:
int main()
{
std::set s;
s.insert(Foo(1, 6));
s.insert(Foo(1, 5));
s.insert(Foo(3, 4));
s.insert(Foo(2, 4));
for (auto const &foo : s)
std::cout << foo.val1 << " " << foo.val2 << std::endl;
return 0;
}
Output:
3 4
1 5
1 6
Here, the second Foo
object where val2
is 4 is missing, because a std::set
only allows for unique entries. Whether entries are unique is decided based on the provided <
operator. In this example, the <
operator compares the val2
members to each other. Therefore, two Foo
objects are equal, if their val2
members have the same value.
So, your choice depends on whether or not you want to store Foo
objects that may be equal based on the <
operator.
Code on Ideone