According to this page, I can achieve constant time insertion if I use
iterator std::set::insert ( iterator position, const value_type& x );
<
Is it cheating to run a test instead of reading through library specifications?
For g++-4.4 -O2
for the integers 0 <= i < 5000000
my running times for
standard insertion are
real 0m14.952s
user 0m14.665s
sys 0m0.268s
and my running times for insertion using end()
as hint are
real 0m4.373s
user 0m4.148s
sys 0m0.224s
Insertion at end() - 1
is just as fast as far as I can tell, but it is more cumbersome to use because end() - 1
is an illegal operation (you have to use operator--()
) and it crashes if the set happens to be empty.
#include
typedef std::set Set;
void insert_standard(Set& xs, int x)
{
xs.insert(x);
}
void insert_hint_end(Set& xs, int x)
{
xs.insert(xs.end(), x);
}
int main()
{
const int cnt = 5000000;
Set xs;
for (int i = 0; i < cnt; i++) {
// insert_hint_end(xs, i);
insert_standard(xs, i);
}
}