0%

vector取size问题

缘起

最近迷上了sizeof,感觉比sizeof()炫酷多了

1
2
3
int buff[1024];
// 对buff一系列操作
int n = sizeof buff;

冲突

然后我就习惯性地使用着sizeof,直到我写了如下代码

1
2
3
4
5
6
7
8
9
int tmp[10] = {1,-2,3,10,-4,7,2,-5};
vector<int> a(tmp,tmp+8);
int n = -1;
if(!array.empty()) n = sizeof array;
if(n<=0) return 0;
for(int i=0;i<n;i++) cout<< array[i] << " "; cout<<endl;

// output :
// 1 -2 3 10 -4 7 2 -5 0 0 -1864443732 469806420 1 0 1376592 0 -1046104771 16040918 -1864443732 402697557 1385904 0 1376592 0

分析

原因分析:

sizeof是对精确的数据类型操作

sizeof(type)
sizeof expression

1) Yields the size in bytes of the object representation of type.
2) Yields the size in bytes of the object representation of the type of expression, if that expression is evaluated.

而vector是一个类

A std::vector is a class. It’s not the actual data, but a class that manages it.
Use std::vector.size() to get the size of the actual data.

所以应该是

1
2
3
4
5
6
7
int tmp[10] = {1,-2,3,10,-4,7,2,-5};
vector<int> a(tmp,tmp+8);
int n = -1;
if(!array.empty()) n = array.size();
if(n<=0) return 0;
for(int i=0;i<n;i++) cout<< array[i] << " "; cout<<endl;
// output : 1 -2 3 10 -4 7 2 -5