C++ STL - Vector

本文深入解析C++标准库中的Vector容器,涵盖其定义、构造、成员函数及模板函数等内容,通过示例展示如何使用Vector进行高效的数据管理和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vector

定义容器类模板向量和多个支持模板。
vector 是将给定类型的元素组织到线性序列中的容器。 它使用户可以快速随机访问任何元素,并动态添加到序列和动态从序列中删除。 vector 是随机访问性能超出限制时的首选序列容器。
库 <vector 也使用了 #include <initializer_list> 语句。
语法:

namespace std {
template <class Type, class Allocator>
class vector;
template <class Allocator>
class vector<bool>;

template <class Allocator>
struct hash<vector<bool, Allocator>>;

// TEMPLATE FUNCTIONS
template <class Type, class Allocator>
bool operator== (
    const vector<Type, Allocator>& left,
    const vector<Type, Allocator>& right);

template <class Type, class Allocator>
bool operator!= (
    const vector<Type, Allocator>& left,
    const vector<Type, Allocator>& right);

template <class Type, class Allocator>
bool operator<(
    const vector<Type, Allocator>& left,
    const vector<Type, Allocator>& right);

template <class Type, class Allocator>
bool operator> (
    const vector<Type, Allocator>& left,
    const vector<Type, Allocator>& right);

template <class Type, class Allocator>
bool operator<= (
    const vector<Type, Allocator>& left,
    const vector<Type, Allocator>& right);

template <class Type, class Allocator>
bool operator>= (
    const vector<Type, Allocator>& left,
    const vector<Type, Allocator>& right);

template <class Type, class Allocator>
void swap (
    vector<Type, Allocator>& left,
    vector<Type, Allocator>& right);

}  // namespace std

参数

名称描述
Type向量中所存储的数据类型的模板参数
Allocator负责分配和释放内存的已存储分配器对象的模板参数
left比较操作中的第一个(左)向量
right比较操作中的第二个(右)向量。

运算符

  • operator! = (测试运算符左侧的向量对象是否等于右侧的向量对象。)
  • operator< (测试运算符左侧的向量对象是否小于右侧的向量对象。)
  • operator<= (测试运算符左侧的向量对象是否小于或等于右侧的向量对象。)
  • operator== (测试运算符左侧的向量对象是否等于右侧的向量对象。)
  • operator> (测试运算符左侧的向量对象是否大于右侧的向量对象)
  • operator>= (测试运算符左侧的向量对象是否大于或等于右侧的向量对象。)
bool operator>(const vector<Type, Allocator>& left, const vector<Type, Allocator>& right);
#include <iostream>
#include <vector>
using namespace std;



int main()
{
	vector <int> v1, v2;
    v1.push_back(1);
    v2.push_back(2);
    cout << "operator != :" << endl;
    if (v1 != v2)
    {
        cout << "Vectors not equal." << endl;
    }  
    else
    {
        cout << "Vectors equal." << endl;
    }

    cout << "operator < :" << endl;
    v1.push_back(2);
    v1.push_back(4);
    v2.push_back(3);
    if (v1 < v2)
    {
        cout << "Vector v1 is less than vector v2." << endl;
    }
    else
    {
        cout << "Vector v1 is not less than vector v2." << endl;
    }
       
    cout << "operator <= :" << endl;
    if (v1 <= v2)
    {
        cout << "Vector v1 is less than or equal to vector v2." << endl;
    }
    else
    {
        cout << "Vector v1 is greater than vector v2." << endl;
    }

    cout << "operator == :" << endl;
    vector<int> v3, v4;
    v3.push_back(1);
    v4.push_back(1);
    if (v3 == v4)
    {
        cout << "Vectors equal." << endl;
    }
    else
    {
        cout << "Vectors not equal." << endl;
    }

    cout << "operator > :" << endl;

    if (v1 > v2)
    {
        cout << "Vector v1 is greater than vector v2." << endl;
    }
    else
    {
        cout << "Vector v1 is not greater than vector v2." << endl;
    }

    cout << "operator >= :" << endl;
    if (v1 >= v2)
    {
        cout << "Vector v1 is greater than or equal to vector v2." << endl;
    }
    else
    {
        cout << "Vector v1 is less than vector v2." << endl;
    }

	return 0;
}

在这里插入图片描述

vector 类

C++标准库 vector 类是序列容器的类模板。 矢量以线性方式存储给定类型的元素,并允许快速随机访问任何元素。 当随机访问性能处于高级版时,矢量是序列的首选容器。
语法:

template <class Type, class Allocator = allocator<Type>>
class vector

参数
类型 Type
要存储在矢量中的元素数据类型
分配器 allocator
表示所存储分配器对象的类型,该分配器对象封装有关矢量的内存分配和解除分配的详细信息。 此参数为可选参数,默认值为 allocator。

vector 构造:

vector();
explicit vector(const Allocator& allocator);
explicit vector(size_type count);
vector(size_type count, const Type& value);
vector(size_type count, const Type& value, const Allocator& allocator);

vector(const vector& source);
vector(vector&& source);
vector(initializer_list<Type> init_list, const Allocator& allocator);

template <class InputIterator>
vector(InputIterator first, InputIterator last);
template <class InputIterator>
vector(InputIterator first, InputIterator last, const Allocator& allocator);

参数:

allocator : 要用于此对象的分配器类。 get_allocator 返回对象的分配器类。
count: 构造的矢量中的元素数。
value:构造的矢量中的元素值。
source :要成为副本的构造的矢量中的矢量。
first:要复制的元素范围内的第一个元素的位置。
last:要复制的元素范围外的第一个元素的位置。
init_list:包含要复制的元素的 initializer_list。

备注
所有构造函数都存储一个分配器对象(分配器)并初始化向量。
前两个构造函数指定一个空初始矢量。 第二个构造函数显式指定要使用的分配器类型(分配器)。
第三个构造函数指定类 Type的默认值的元素的指定数目(计数)重复。
第四个和第五个构造函数指定值值的(count)元素的重复。
第六个构造函数指定矢量源的副本。
第七个构造函数移动矢量源。
第八个构造函数使用 initializer_list 指定元素。
第九个和第十个构造函数复制矢量的范围(first、last)。
示例:

#include<iostream>
#include<vector>

using namespace std;

//构造函数

int main(void)
{
    vector <int>::iterator v1_Iter, v2_Iter, v3_Iter, v4_Iter, v5_Iter, v6_Iter;

    // 创建一个空向量v0
    vector <int> v0;

    // 创建一个向量v1,其中3个元素的默认值为0
    vector <int> v1(3);

    // 用值是2的5个元素创建一个向量v2
    vector <int> v2(5, 2);

    // 用向量v2的分配器创建一个向量v3,它有3个值为1的元素
    vector <int> v3(3, 1, v2.get_allocator());

    // 创建一个拷贝,向量v4 从 向量v2中
    vector <int> v4(v2);

    // 创建一个新的临时向量来演示复制范围
    vector <int> v5(5);
    for (auto i : v5) {
        v5[i] = i;
    }

    // 通过复制范围v5[first, last]创建一个vector v6
    vector <int> v6(v5.begin() + 1, v5.begin() + 3);

    cout << "v1 =";
    for (auto& v : v1) {
        cout << " " << v;
    }
    cout << endl;

    cout << "v2 =";
    for (auto& v : v2) {
        cout << " " << v;
    }
    cout << endl;

    cout << "v3 =";
    for (auto& v : v3) {
        cout << " " << v;
    }
    cout << endl;
    cout << "v4 =";
    for (auto& v : v4) {
        cout << " " << v;
    }
    cout << endl;

    cout << "v5 =";
    for (auto& v : v5) {
        cout << " " << v;
    }
    cout << endl;

    cout << "v6 =";
    for (auto& v : v6) {
        cout << " " << v;
    }
    cout << endl;

    // 将向量v2移动到向量v7
    vector <int> v7(move(v2));
    vector <int>::iterator v7_Iter;

    cout << "v7 =";
    for (auto& v : v7) {
        cout << " " << v;
    }
    cout << endl;

    vector<int> v8{ { 1, 2, 3, 4 } };
    for (auto& v : v8) {
        cout << " " << v;
    }
    cout << endl;
}

在这里插入图片描述

Typedef:

allocator_type一个类型,它表示矢量对象的 allocator 类。allocator_type 是模板参数 Allocator 的同义词
const_iterator一个类型,它提供可读取矢量中 const 元素的随机访问迭代器。类型 const_iterator 不能用于修改元素的值。
const_pointer一个类型,它提供指向矢量中 const 元素的指针。类型 const_pointer 不能用于修改元素的值
const_reference一种类型,它提供对存储在向量中的const元素的引用。 它用于读取和执行const运算。类型 const_reference 不能用于修改元素的值
const_reverse_iterator一个类型,它提供可读取矢量中任何 const 元素的随机访问迭代器。类型 const_reverse_iterator 无法修改元素的值,它用于反向循环访问矢量。
difference_type一个类型,它提供矢量中两个元素的址间的差异。difference_type 也可以被描述为两个指针之间的元素数,因为指向一个元素的指针包含其地址。
Iterator一个类型,它提供可读取或修改向量中任何元素的随机访问迭代器。iterator 类型可用于修改元素的值
pointer一个类型,提供指向向量中元素的指针。pointer 类型可用于修改元素的值
reference一个类型,它提供对向量中存储的元素的引用。
reverse_iterator一个类型,它提供可读取或修改反向矢量中的任意元素的随机访问迭代器。
size_type一个类型,它计算矢量中的元素数目。
value_type一个类型,它代表向量中存储的数据类型。
#include<iostream>
#include<vector>

using namespace std;

int main(void)
{
	cout << "allocator_type (一个类型,它代表向量对象的分配器类):" << endl;
    // v1 v2, 使用默认分配器 (allocator<int>),默认可以不写在代码中
    vector<int> v1;
    vector<int, allocator<int> > v2 = vector<int, allocator<int> >(allocator<int>());
    //v3将使用与v1相同的分配器类
    vector <int> v3(v1.get_allocator());//get_allocator() 返回向量所使用的分配器

    vector<int>::allocator_type xvec = v3.get_allocator(); //get_allocator() 返回向量所使用的分配器
    cout << typeid(xvec).name() << endl;


    cout << "const_iterator (一个类型,它提供可读取矢量中 const 元素的随机访问迭代器):" << endl;
    vector<int> vc1{1,2,3,4,5};
    for (vector<int>::const_iterator c_itb = vc1.begin(); c_itb != vc1.end(); c_itb++)
    {
        cout << *c_itb << " ";
    }
    cout << endl;

    cout << "const_pointer (一个类型,它提供指向矢量中 const 元素的指针):" << endl;
    vector<int>::const_pointer c_ptr = &*vc1.begin();
    size_t n = 0;
    while (n<vc1.size())
    {
        cout << *(c_ptr+n) << " ";
        n++;
    }
    cout << endl;

    cout << "const_reference (一种类型,它提供对存储在向量中的const元素的引用。 它用于读取和执行const运算):" << endl;
    v1.push_back(10);
    v1.push_back(20);

    const vector <int> v4 = v1;
    const int& i = v4.front();
    const int& j = v4.back();
    cout << "The first element is " << i << endl;
    cout << "The second element is " << j << endl;
    //面的行会导致一个错误,因为v4是const
    //v4.push_back( 30 );//添加元素

    cout << "const_reverse_iterator (一个类型,它提供可读取矢量中任何 const 元素的随机访问迭代器):" << endl;
    vector<int>::const_reverse_iterator cr_itb = vc1.rbegin();
    cout << typeid(cr_itb).name() << endl;
    for (cr_itb; cr_itb != vc1.rend(); cr_itb++)
    {
        cout << *cr_itb << " ";
    }
    cout << endl;

    cout << "difference_type (一个类型,它提供引用同一向量中元素的两个迭代器之间的差异):" << endl;
    vector <int> c1;
    vector <int>::iterator c1_Iter, c2_Iter;

    c1.push_back(30);
    c1.push_back(20);
    c1.push_back(30);
    c1.push_back(10);
    c1.push_back(30);
    c1.push_back(20);

    c1_Iter = c1.begin();
    c2_Iter = c1.end();
   

    vector <int>::difference_type   df_typ1, df_typ2, df_typ3;

    df_typ1 = count(c1_Iter, c2_Iter, 10);
    df_typ2 = count(c1_Iter, c2_Iter, 20);
    df_typ3 = count(c1_Iter, c2_Iter, 30);
    cout << "The number '10' is in c1 collection " << df_typ1 << " times.\n";
    cout << "The number '20' is in c1 collection " << df_typ2 << " times.\n";
    cout << "The number '30' is in c1 collection " << df_typ3 << " times.\n";

    cout << "iterator (一个类型,它提供可读取或修改向量中任何元素的随机访问迭代器):" << endl;
    for (; c1_Iter != c2_Iter; c1_Iter++)
    {
        (*c1_Iter) /= 10;//改变元素的值
    }
    for (auto i : c1)
    {
        cout << i << " ";
    }
    cout << endl;

    cout << "pointer (一个类型,提供指向向量中元素的指针):" << endl;
    vector<int>::pointer ptr = &c1[0];
    for (int n=0; n<c1.size(); n++)
    {
        *ptr = (*ptr) + 20;
        cout << *ptr << " ";
        ptr++;
    }

    cout << "reference (一个类型,它提供对向量中存储的元素的引用):" << endl;
    vector<int>::reference refb = vc1.at(0);
    cout << refb << endl;
    refb = 100;
    cout << vc1.at(0) << endl;
    cout << vc1[0] << endl;

    cout << "reverse_iterator (一个类型,它提供可读取或修改反向矢量中的任意元素的随机访问迭代器):" << endl;
    vector<int>::reverse_iterator ritb = vc1.rbegin();
    for (; ritb != vc1.rend(); ritb++)
    {
        cout << *ritb <<" ";
    }
    cout << endl;
    cout << "size_type (一个类型,它计算矢量中的元素数目):" << endl;
    vector<int>::size_type st1 = vc1.size();
    vector<int>::size_type st2 = c1.capacity();

    cout << st1 << "  " << st2 << endl;

    cout << "value_type (一个类型,它代表向量中存储的数据类型):" << endl;
    vector<int>::value_type vt;
    vt = 100;
    cout << typeid(vt).name() << endl;
    cout << vt << endl;

    cout << endl;




	return 0;
}

在这里插入图片描述
成员函数:

assign清除矢量并将指定的元素复制到该空矢量。
at返回对矢量中指定位置的元素的引用。
back返回对向量中最后一个元素的引用。
begin对该向量中第一个元素返回随机访问迭代器。
capacity返回在不分配更多的存储的情况下向量可以包含的元素数。
cbegin返回指向向量中第一个元素的随机访问常量迭代器。
cend返回一个随机访问常量迭代器,它指向刚超过矢量末尾的位置
crbegin返回一个指向反向矢量中第一个元素的常量迭代器。
crend返回一个指向反向矢量末尾的常量迭代器。
clear清除向量的元素。
data返回指向向量中第一个元素的指针。
emplace将就地构造的元素插入到指定位置的向量中。
emplace_back将一个就地构造的元素添加到向量末尾。
empty测试矢量容器是否为空。
end返回指向矢量末尾的随机访问迭代器。
erase从指定位置删除向量中的一个元素或一系列元素。
front返回对向量中第一个元素的引用。
get_allocator将对象返回到矢量使用的 allocator 类。
insert将一个元素或多个元素插入到指定位置的向量中。
max_size返回向量的最大长度。
pop_back删除矢量末尾处的元素。
push_back在矢量末尾处添加一个元素。
rbegin返回指向反向向量中第一个元素的迭代器。
rend返回一个指向反向矢量末尾的迭代器。
reserve保留向量对象的最小存储长度。
resize为矢量指定新的大小。
shrink_to_fit放弃额外容量。
size返回向量中的元素数量。
swap交换两个向量的元素。

示例:

#include<iostream>
#include<vector>

using namespace std;

struct obj
{
    obj(int n1, double d1):n(n1),d(d1) {}
    int n;
    double d;
};

int main(void)
{
    vector<int> v1{ 1,2,3,4,5,6,7,8,9,0 };

    cout << "begin() & end() :第一个元素返回随机访问迭代器 & 矢量末尾的随机访问迭代器:" << endl;
    for (auto itb = v1.begin(), ite = v1.end(); itb != ite; itb++)
    {
        *itb += 5;//修改元素的值
        cout << *itb << " ";
    }
    cout << endl;

    cout << "max_size() & size() :向量的最大长度 & 向量中的元素数量:" << endl;
    cout << "v1最大长度= " << v1.max_size() << ";  v1元素数量=" << v1.size() << endl;

    cout << "back() & front(): 返回对向量中最后一个元素的引用 & 返回对向量中第一个元素的引用:" << endl;
    int &back = v1.back(), &front = v1.front();
    cout << "v1 第一个元素=" << &front <<":"<<front<< " ; v1 最后一个元素=" << &back<<":"<<back << endl;
    back = 100;//修改元素的值
    front = 200;
    for (auto& i : v1)
    {
        cout << i << " ";
    }
    cout << endl;

    cout << "cbegin() & cend() : 返回常量迭代器,不能修改元素的值:" << endl;
    for (auto citb = v1.cbegin(), cite = v1.cend(); citb != cite; citb++)
    {
        cout << *citb << " ";
    }
    cout << endl;

    cout << "rbegin() & rend() :返回指向反向向量中第一个元素的迭代器 & 返回一个指向反向矢量末尾的迭代器:" << endl;
    for (auto ritb = v1.rbegin(), rite = v1.rend(); ritb != rite; ritb++)
    {
        cout << *ritb << " ";
    }
    cout << endl;

    cout << "crbegin() & crend() :反向常量迭代器,不能修改元素的值:" << endl;
    for (auto critb = v1.crbegin(), crite = v1.crend(); critb != crite; critb++)
    {
        cout << *critb << " ";
    }
    cout << endl;

    cout << "data() :返回指向向量中第一个元素的指针:" << endl;
    vector<int>::pointer v1_ptr;//指针
    vector<int>::const_pointer v1_cPtr;//常量指针
    cout << "The vector v1 contains elements:";
    v1_cPtr = v1.data();
    for (size_t n = v1.size(); 0 < n; --n, v1_cPtr++)
    {
        cout << " " << *v1_cPtr;
    }
    cout << endl;
    cout << "The vector v1 now contains elements:";
    v1_ptr = v1.data();
    *v1_ptr = 20;
    for (size_t n = v1.size(); 0 < n; --n, v1_ptr++)
    {
        cout << " " << *v1_ptr;
    }
    cout << endl;

    cout << "at() :返回对矢量中指定位置的元素的引用。:" << endl;
    //at() 和 [] 区别 : at() 对于下标溢出可以用异常捕获而 [] 则直接引起程序崩溃
    cout << "v1.at(0)=" << v1.at(0) << " ; v1[0]=" << v1[0] << endl;
    cout << "v1.at(3)=" << v1.at(3) << " ; v1[3]=" << v1[3] << endl;

    cout << "empty() :判断容器是否为空 如果向量为空,则为true ;如果矢量不为空,则为 false:" << endl;
    bool b = v1.empty();
    if (!b)
    {
        cout << "v1 is not empty" << endl;
    }
   

    cout << "clear() :清除向量的元素:" << endl;
    v1.clear();
    b = v1.empty();
    if (b)
    {
        cout << "v1 is empty" << endl;
    }
    for (auto& i : v1)
    {
        cout << i << " ";
    }
    cout << endl;

    cout << " capacity() :返回在不分配更多的存储的情况下向量可以包含的元素数:" << endl;
    vector<int> v2;
    v2.push_back(1);
    cout << "The length of storage allocated is "<< v2.capacity() << "." << endl;

    v2.push_back(2);
    cout << "The length of storage allocated is now " << v2.capacity() << "." << endl;

    cout << "emplace() :将就地构造的元素插入到指定位置的向量中: 任何插入操作都可能会消耗大量资源" << endl;
    v2.push_back(10);
    v2.push_back(20);
    vector<vector<int>> vv1;
    //通过移动 v2 初始化一个 向量
    vv1.emplace(vv1.begin(), move(v2));
    if (vv1.size() != 0 && vv1[0].size() != 0)
    {
        cout << "vv1[0]=";
        for (vector<int>::iterator Iter = vv1[0].begin(); Iter != vv1[0].end(); Iter++)
        {
            cout << " " << *Iter;
        }
        cout << endl;
    }

    cout << "emplace_back(): 将一个就地构造的元素添加到向量末尾:" << endl;
   
    vector<obj> v;
    v.emplace_back(1, 3.14); // obj in created in place in the vector
    v.emplace_back(2, 6.18);
    for (auto itb = v.begin(); itb != v.end(); itb++)
    {
        obj o = (obj)(*itb);
        cout << o.n << " : " << o.d << endl;
    }

    cout << "pop_back() : 删除矢量末尾处的元素:" << endl;
    v.pop_back();
    for (auto itb = v.begin(); itb != v.end(); itb++)
    {
        cout << (*itb).n << " : " << (*itb).d << endl;
    }

    cout << "insert() 将一个元素、多个元素或一系列元素插入到指定位置的向量中:" << endl;
    vector <int>::iterator Iter;
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);

    cout << "v1 =";
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)
        cout << " " << *Iter;
    cout << endl;

    v1.insert(v1.begin() + 1, 40);//将 40 插入在第[1]个位置
    cout << "v1 =";
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)
        cout << " " << *Iter;
    cout << endl;

    v1.insert(v1.begin() + 2, 4, 50);//从第[2]开始插入4个50
    cout << "v1 =";
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)
        cout << " " << *Iter;
    cout << endl;

    const auto v3 = v1;
    v1.insert(v1.begin() + 1, v3.begin() + 2, v3.begin() + 4);//从 v1[1] 开始插入 数据 v3[2] -- v3[4] 共2个数据
    cout << "v1 =";
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)
        cout << " " << *Iter;
    cout << endl;

    vector < vector <int> > vv2;

    vv2.insert(vv2.begin(), move(v1));
    if (vv2.size() != 0 && vv2[0].size() != 0)
    {
        cout << "vv2[0] =";
        for (Iter = vv2[0].begin(); Iter != vv2[0].end(); Iter++)
            cout << " " << *Iter;
        cout << endl;
    }

    cout << "erase() 从指定位置删除向量中的一个元素或一系列元素:" << endl;
    vector<int> v5{10,20,30,40,50,60,70,80,90};

    v5.erase(v5.begin());
    cout << "v5 =";
    for (Iter = v5.begin(); Iter != v5.end(); Iter++)
        cout << " " << *Iter;
    cout << endl;

    v5.erase(v5.begin() + 1, v5.begin() + 3);
    cout << "v5 =";
    for (Iter = v5.begin(); Iter != v5.end(); Iter++)
        cout << " " << *Iter;
    cout << endl;

    cout << "reserve() :为向量对象保留最小的存储长度,必要时为其分配空间:" << endl;
    v5.push_back(1);
    cout << "Current capacity of v5 = "<< v5.capacity() << endl;
    v5.reserve(20);
    cout << "Current capacity of v5 = "<< v5.capacity() << endl;

    return 0;
}

在这里插入图片描述
resize:为矢量指定新的大小

#include <iostream>
#include <vector>
#include <string>
// vectorsizing.cpp
// compile with: /EHsc /W4
// Illustrates vector::reserve, vector::max_size,
// vector::resize, vector::resize, and vector::capacity.
//
// Functions:
//
//    vector::max_size - 返回向量可以容纳的元素的最大数目。
//
//    vector::capacity - 返回已为其分配内存的元素数量。
//
//    vector::size - 返回向量中元素的个数.
//
//    vector::resize - 为vector重新分配内存,如果新大小大于现有大小,则保留其内容
//
//    vector::reserve - 为vector分配元素以确保最小大小,如果新大小大于现有大小,则保留其内容。
//
//    vector::push_back - 将一个元素追加(插入)到一个向量的末尾,并在必要时为其分配内存。
//
//

// 调试器不能处理长度超过255个字符的符号。
// c++标准库通常会创建比这更长的符号
// The warning can be disabled: #pragma warning(disable:4786)

using namespace std;

template <typename C> void print(const string& s, const C& c) {
    cout << s;

    for (const auto& e : c) {
        cout << e << " ";
    }
    cout << endl;
}

void printvstats(const vector<int>& v) {
    cout << "   the vector's size is: " << v.size() << endl;
    cout << "   the vector's capacity is: " << v.capacity() << endl;
    cout << "   the vector's maximum size is: " << v.max_size() << endl;
}

int main()
{
    // 声明一个以0个元素开始的向量。
    vector<int> v;

    // 显示有关向量的统计信息.
    cout << endl << "在声明一个空向量之后:" << endl;
    printvstats(v);
    print("   the vector's contents: ", v);

    // 在向量的末尾加上一个元素。
    v.push_back(-1);
    cout << endl << "添加元素后:" << endl;
    printvstats(v);
    print("   the vector's contents: ", v);

    for (int i = 1; i < 10; ++i) {
        v.push_back(i);
    }
    cout << endl << "添加10个元素后:" << endl;
    printvstats(v);
    print("   the vector's contents: ", v);

    v.resize(6);
    cout << endl << "在调整到6个没有初始值的元素后:" << endl;
    printvstats(v);
    print("   the vector's contents: ", v);

    v.resize(9, 999);
    cout << endl << "调整到9个元素,初始值为999:" << endl;
    printvstats(v);
    print("   the vector's contents: ", v);

    v.resize(12);
    cout << endl << "调整到12个元素而没有初始值:" << endl;
    printvstats(v);
    print("   the vector's contents: ", v);

    // 确保至少有1000个元素的空间
    v.reserve(1000);
    cout << endl << "After vector::reserve(1000):" << endl;
    printvstats(v);

    // 确保至少有2000个元素的空间。
    v.resize(2000);
    cout << endl << "After vector::resize(2000):" << endl;
    printvstats(v);

    return 0;
}

在这里插入图片描述
shrink_to_fit: 放弃额外容量

#include <iostream>
#include <vector>
#include <string>


int main()
{
    using namespace std;
    vector <int> v1;
    //vector <int>::iterator Iter;

    v1.push_back(1);
    cout << "Current capacity of v1 = "
        << v1.capacity() << endl;
    v1.reserve(20);
    cout << "Current capacity of v1 = "
        << v1.capacity() << endl;
    v1.shrink_to_fit();
    cout << "Current capacity of v1 = "
        << v1.capacity() << endl;

    return 0;
}

在这里插入图片描述
swap:交换两个向量的元素


int main()
{
    using namespace std;
    vector <int> v1, v2;

    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(3);

    v2.push_back(10);
    v2.push_back(20);

    cout << "The number of elements in v1 = " << v1.size() << endl;
    cout << "The number of elements in v2 = " << v2.size() << endl;
    cout << endl;

    v1.swap(v2);

    cout << "The number of elements in v1 = " << v1.size() << endl;
    cout << "The number of elements in v2 = " << v2.size() << endl;

    return 0;
}

在这里插入图片描述

vector 测试 Dome

#include "VectorTest.h"
#include"TestFunc.h"
#include<iostream>
#include<vector>
#include<cstdlib>
#include<ctime>
#include<cstdio>
#include<algorithm>

using namespace std;

void vector_test_01::Vector_test(long& size)
{
	cout << "开始 vector test ... ... ...\n\n" << endl;
	vector<string> vec;
	char buf[10] = {0};
	clock_t timeStart = clock();
	for (long i = 0; i < size; i++)
	{
		try
		{
			snprintf(buf, 10, "%d", rand() % 0xFFFF);
			vec.push_back(string(buf));
		}
		catch(exception& p)
		{
			cout << "i= " << i << " " << p.what() << endl;
			abort();
		}
	}

	cout << size << " 个元素,初始化:" << clock() - timeStart << " 毫秒" << endl;

	cout << "成员函数:\n" << endl;

	cout << "元素个数 - vector.size(): " << vec.size() << endl;
	cout << "第一个元素 - vector.front(): " << vec.front() << endl;
	cout << "最后一个元素 - vector.back(): " << vec.back() << endl;
	cout << "容器首地址 - vector.data(): " << vec.data() << endl;
	cout << "判断容器是否为空 - vec.empty(): " << vec.empty() << endl;
	cout << "容器元素总量 - vec.capacity(): " << vec.capacity() << endl;

	string target = Get_a_target_string();
	timeStart = clock();
	auto ptr_Item = ::find(vec.begin(), vec.end(), target);
	cout << "::find() , milli-seconds : " << clock() - timeStart << endl;
	if (ptr_Item != vec.end())
	{
		cout << "Found ," << *ptr_Item << endl;
	}
	else
	{
		cout << "NO Found ! " << endl;
	}

	timeStart = clock();

	sort(vec.begin(), vec.end());

	string* ptr_str = (string*)bsearch(&target, vec.data(), vec.size(), sizeof(string), compareStrings);

	cout << "sort() + bsearch() , milli-seconds :" << clock() - timeStart << endl;
	if (ptr_str != nullptr)
	{
		cout << "Found ," << *ptr_str << endl;
	}
	else
	{
		cout << "NO Found ! " << endl;
	}

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值