1、empty() 判断容器是否为空。为空返回真,不为空返回假。
2、capacity() 返回容器的容量
3、size() 返回容器中元素的个数。元素个数不一定等于容器容量。
4、resize(int num) 重新指定容器的长度为num。若容器变长,以默认值0填充新位置。如果容器变短,则末尾超出容器长度的元素被删除。
5、resize(int num, elem) 重新指定容器的长度为num。若容器变长,以elem值填充新位置。如果容器变短,则末尾超出容器长度的元素被删除。
一、empty() 判断容器是否为空。为空返回真,不为空返回假。
#include<iostream>
using namespace std;
#include<vector>
int main()
{
vector<int> v;
if(v.empty())
{
cout << "Vector is empty" << endl;
}
else
{
cout << "Vector isn't empty" << endl;
}
system("pause");
}
运行结果:
Vector is empty
请按任意键继续. . .
二、capacity()和size()
#include<iostream>
using namespace std;
#include<vector>
int main()
{
vector<int> v;
for (int i = 1; i <= 5; i++)
{
v.push_back(i);
}
cout << "The capacity of vector is " << v.capacity() << endl;
cout << "The size of vector is " << v.size() << endl;
system("pause");
}
运行结果:
The capacity of vector is 8
The size of vector is 5
请按任意键继续. . .
会发现,尾插法存入数据时,容器的capacity会大于size。
三、**resize()**重新指定容器的长度为num
#include<iostream>
using namespace std;
#include<vector>
void printVector(vector<int> &v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << ' ';
}
cout << endl;
}
int main()
{
//用尾插法存入5个数
vector<int> v;
for (int i = 1; i <= 5; i++)
{
v.push_back(i);
}
cout << "The capacity of vector is " << v.capacity() << endl;
cout << "The size of vector is " << v.size() << endl;
printVector(v);
cout << endl;
//重新指定大小,该大小大于原容器容量,新位置用10填充
v.resize(10, 100);
cout << "The capacity of vector is " << v.capacity() << endl;
cout << "The size of vector is " << v.size() << endl;
printVector(v);
cout << endl;
//重新指定大小,该大小小于原容量大小
v.resize(2);
cout << "The capacity of vector is " << v.capacity() << endl;
cout << "The size of vector is " << v.size() << endl;
printVector(v);
system("pause");
}
运行结果:
The capacity of vector is 8
The size of vector is 5
1 2 3 4 5
The capacity of vector is 10
The size of vector is 10
1 2 3 4 5 100 100 100 100 100
The capacity of vector is 10
The size of vector is 2
1 2
请按任意键继续. . .
C++容器操作详解
本文详细介绍了C++中容器的几种关键操作,包括empty()用于判断容器是否为空,capacity()和size()分别用于获取容器的容量和元素数量,以及resize()如何改变容器的长度并填充新位置或删除超出长度的元素。
839

被折叠的 条评论
为什么被折叠?



