C ++コンテナベクトル関連の操作
1.容量
ベクターの容量は常にそのサイズ以上です。容量がサイズに等しくなると、いっぱいになります。次に新しい要素がある場合は、ベクターコンテナー全体が別の場所を見つける必要があります。 。
1. c.capacity(); ...メモリスペースを再割り当てせずにcによって保存できる要素の数
2.c.reserve(); ...少なくともn個の要素を保持できるメモリスペースを割り当てます
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
cout << v.capacity() << endl;
}
出力:
1
2
3
4
6
6
9
9
9
13
请按任意键继续. . .
2、ベクトルの構築と割り当て
//赋值
vector<int> v1;
vector<int> v2(10, 100);
printVector(v2);
vector<int> v3(v2.begin(), v2.end());
printVector(v3);
//赋值
vector<int> v4;
v4.assign(v3.begin(), v3.end());//等价于v4=v3
printVector(v4);
int arr[] = {
2,3,4,1,9 };
vector<int> v5(arr, arr + sizeof(arr) / sizeof(int));
//swap交换
v4.swap(v5);
printVector(v4);
出力:
100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100
2 3 4 1 9
请按任意键继续. . .
3、ベクトルサイズ操作
vector<int> v1 = {
1,2,5,6,9,56,4,5,11,6 };
cout << "v1中元素的个数为:" << v1.size() << endl;//size返回容器中元素的个数
if (v1.empty())//判定容器是否为空
{
cout << "v1为空" << endl;
}
else
{
cout << "v1不为空" << endl;
}
//重新指定容器长度 resize
v1.resize(11);//重新指定容器的长度,若容器长了,则用默认值填充容器的长度
printVector(v1);
v1.resize(3);//如果容器短了,则末尾超出容器长度的元素被删除
printVector(v1);
v1.resize(15, 100);//第二个参数是默认填充的值
printVector(v1);
出力:
v1中元素的个数为:10
v1不为空
1 2 5 6 9 56 4 5 11 6 0
1 2 5
1 2 5 100 100 100 100 100 100 100 100 100 100 100 100
请按任意键继续. . .
4つのベクトルデータアクセス操作
vector<int> v1 = {
1,2,3,4,5 };
cout << "v1的第一个元素:" << v1.front() << endl;
cout << "v1的最后一个元素:" << v1.back() << endl;
出力:
v1的第一个元素:1
v1的最后一个元素:5
请按任意键继续. . .
5、ベクターの挿入および削除操作
vector<int> v1 = {
1,2,3,4,5 };
v1.insert(v1.begin()+1,2, 1000);//第一个参数是迭代器,第二个是个数,第三个是插入元素
printVector(v1);
v1.pop_back();//尾部删除
printVector(v1);
v1.erase(v1.begin());//删除
printVector(v1);
v1.clear();//清空
printVector(v1);
出力:
1 1000 1000 2 3 4 5
1 1000 1000 2 3 4
1000 1000 2 3 4
请按任意键继续. . .
6つの正の順序のトラバーサルと逆の順序のトラバーサル
vector<int> v1 = {
1,2,3,4,5 };
cout << "正序遍历结果:" << endl;
printVector(v1);
cout << "逆序遍历结果:" << endl;
for (vector<int>::reverse_iterator it = v1.rbegin(); it != v1.rend(); it++)//如果使用逆序遍历的话,需要使用reverse_iterator
{
cout << *it << " ";
}
出力:
正序遍历结果:
1 2 3 4 5
逆序遍历结果:
5 4 3 2 1 请按任意键继续. . .