For vector usage, the additional time consumed by copying data to prevent reallocate memory.
The following two combinations can be used to prevent reallocate.
1. Vector: resize () using array index
2. Vector: Reserve () Use push_back ().
So I tested these two cases on the Windows 2003 platform, and compared them with 3 in which push_back () is directly used without memory reservation:
# Deprecision Max 100000000
Void testpushback ()
{
Clock_t start = clock ();
Vector <int> C;
// A. Reserve (max );
For (INT I = 0; I <Max; I ++)
C. push_back (I );
Cout <clock ()-start <Endl;
Cout <C. Size () <"" <C. Capacity () <Endl;
Start = clock ();
Vector <int>;
A. Reserve (max );
For (INT I = 0; I <Max; I ++)
A. push_back (I );
Cout <clock ()-start <Endl;
Cout <A. Size () <"" <A. Capacity () <Endl;
Start = clock ();
Vector <int> B;
B. Resize (max );
For (INT I = 0; I <Max; I ++)
B [I] = I;
Cout <clock ()-start <Endl;
Cout <B. Size () <''<B. Capacity () <Endl;
}
The test results are as follows:
18859100000000 13621656718172100000000 1000000003313100000000 press any key to continue...
It is found that the combination of reserve and push_back () on window2003 is similar to that of direct push_back,
The combination of resize () and array index has great performance advantages.
PS. Later, the same test was performed on the Linux rh64 platform.
The test result is exactly the opposite to that in window2003. The combination of resize () and array index takes a longer time than the other two.
It seems that the implementation of the platform is quite different.