In my application I have the following requirements -
The data structure will be populated just once with some values (not key/value pairs). The values may be r
I highly recommend you not to use in such this case. set
is binary tree, and unordered_set
is hash table - so they use lots of memory, and have slow iteration speed and bad locality of reference. If you have to insert/remove/find data frequently, set
or unordered_set
good choice, but now you need to just read, store, sort data once and only use data many times.
In this case, sorted vector can be such a good choice. vector
is dynamic array, so it has low overhead.
Just directly, see the code.
std::vector data;
int input;
for (int i = 0; i < 10; i++)
{
std::cin >> input;
data.push_back(input); // store data
}
std::sort(data.begin(), data.end()); // sort data
That's all. All your data is ready.
If you need to remove duplicates like set
, just use unique
- erase
after sorting.
data.erase(
std::unique(data.begin(), data.end()),
data.end()
);
Notice that you should use lower_bound
, upper_bound
and equal_range
rather than find
or find_if
to use the benefits of sorted data.