C++学习-vector容器的容量和大小

Posted 殇堼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++学习-vector容器的容量和大小相关的知识,希望对你有一定的参考价值。

容量永远大于或是等于容器的大小。

判断是否为空------empty ()
返回容器中元素的个数----size()
返回容器的容量----capacity()
重新指定大小-------resize()

#include <iostream>
#include <vector>
using namespace std;

void printvector(vector<int>&v)//引用
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " " ;
	}
	cout << endl;
}
int main() {
	vector<int>v1;//默认构造 或是叫做无惨构造
	for (int i = 0; i < 10; i++) 
	{
		v1.push_back(i);//vector头文件里面就有这个push_back函数,在vector类中作用为在vector尾部加入一个数据
	}
	printvector(v1);

	if (v1.empty()) {
		cout << "容器为空";
	}
	else {
		cout << "容器不为空"<<endl;
		cout << "容器的容量为" << v1.capacity()<<endl;
		cout << "容器的大小为" << v1.size()<<endl;
	}
	
//如果重新指定的比原来要长,默认使用0进行填充。
	v1.resize(12);
	printvector(v1);
	
//如果重新指定比原来的短,超出的部分会被删除掉。
	v1.resize(2);
	printvector(v1);

	return 0;
}


利用重载的版本可以指定默认的填充值

v1.resize(12,9);
	printvector(v1);

以上是关于C++学习-vector容器的容量和大小的主要内容,如果未能解决你的问题,请参考以下文章

C++ 16 vector容器

vector的模拟实现(C++)

c++容器的底层数据结构

C++提高编程STL-vector容器

C++ 提高教程 STL vector容量-vector容量和大小

vector的模拟实现(C++)