我正在开发基于 QT 的应用程序,我需要在动态(QVector)中使用向量。在检查向量的大小时,这比它应该的要高,我用 STL 向量进行了测试,结果是一样的。下面我介绍 STL 向量问题的代码。这种情况使我们无法知道向量的实际大小并正确使用它。怎么修?。谢谢您的帮助。
- 编译器:GCC 4.5.2
- 操作系统:Linux Ubuntu 11.04
- 观察:向量的容量或大小总是以 2 为底的幂
代码是:
double PI = 3.1415926536, delta = PI/(100/2);
vector<double> A(0);
vector<double> B(0);
cout<<"Capacity A = "<<A.capacity()<<"; Capacity B = "<<B.capacity()<<endl;
for (int i = 0; i < 100; i++) {
A.push_back(i*delta);
B.push_back( sin( A[i] ) );
cout<<"A("<<i<<") = " <<A[i]<<"; B("<<i<<") = " <<B[i]<<" "<<"Size A = "<<A.capacity()<<"; Size B = "<<B.capacity()<<endl;
}
for (int i = 0; i < A.capacity(); i++) {
cout<<"A("<<i<<") = " <<A[i]<<"; B("<<i<<") = " <<B[i]<<" "<<"Size A = "<<A.capacity()<<"; Size B = "<<B.capacity()<<endl;
}
cout<<"Size A = "<<A.capacity()<<"; Size B = "<<B.capacity()<<endl;
输出是:
Capacity A = 0; Capacity B = 0
A(0) = 0; B(0) = 0 Size A = 1; Size Y = 1
A(1) = 0.0628319; B(1) = 0.0627905 Size A = 2; Size B = 2
A(2) = 0.125664; B(2) = 0.125333 Size A = 4; Size B = 4
A(3) = 0.188496; B(3) = 0.187381 Size A = 4; Size B = 4
.
A(99) = 6.22035; B(99) = -0.0627905 Size A = 128; Size B = 128
.
A(126) = 0; B(126) = 1.31947 Size A = 128; Size B = 128
A(127) = 0; B(127) = 1.3823 Size A = 128; Size B = 128
Size A = 128; Size B = 128