Let there be a sequence of integers : 3,1,6,3,7,8,2,7 ;
If you insert this sequence in set<int> after sorting the, time taken as a whole ( i.e sorting + inserting) will be lesser than direct insertion into the set without sorting.
If you insert this sequence in set<int> after sorting the, time taken as a whole ( i.e sorting + inserting) will be lesser than direct insertion into the set without sorting.
look at this code
MS VS 2008 Express release:
The stupid way
sort time: 1062
insert time: 3735
sort+insert time: 4797
The smart way
sort time: 969
insert time: 1734
sort+insert time: 2703
MinGW g++.exe -o cc cc.cpp
The stupid way
sort time: 3375
insert time: 9812
sort+insert time: 13281
The smart way
sort time: 3579
insert time: 3453
sort+insert time: 7032
So, i hope you can see, st.insert(st.end(), a[i]) works up to three times faster, if array is sorted.
So, sorting + inserting_your_way is faster than sorting+insert_the_normal_way is faster than inserting_the_normal_way .
Thanks for sharing. :)