vector学习之元素访问at,front,data,back及swap

vector提供的元素访问及容器交换内容有如下操作:

at,访问指定的元素,同时进行越界检查

operator[],访问指定的元素

front 访问第一个元素

back 访问最后一个元素

data 返回指向内存中数组第一个元素的指针

swap交换两个容器内容

代码示例

#include <vector>
#include <iostream>

using namespace std;

void getElement()
{
    vector<int> vec = {1, 3, 6, 8, 9, 12};
    for(int c: vec)
    {
        cout << c << "\t";
    }
    cout << endl;

    cout << "vec.front = " << vec.front() << endl;
    cout << "vec.at(2) = " << vec.at(2) << endl;
    cout << "vec[3] ==== " << vec[3] << endl;
    cout << "vec.data = " << *(vec.data()) << endl;
    cout << "vec.back == " << vec.back() << endl;

    cout << endl;
    vector<int> vec1;
    vector<int> vec2;
    vec1.assign(3, 23);
    vec2.assign({12,14,15,36,67});
    for(int c: vec1)
    {
        cout << c << "\t";
    }
    cout << endl;

    for(int c: vec2)
    {
        cout << c << "\t";
    }
    cout << endl;
    cout << "vec1.size===" << vec1.size() << " vec1.capacity=" << vec1.capacity() << endl;
    cout << "vec2.size===" << vec2.size() << " vec2.capacity=" << vec2.capacity() << endl;
    auto it1 = vec1.begin();
    auto it2 = vec2.begin();
    int &ref1 = vec1.front();
    int &ref2 = vec2.front();
    cout << "*it1 = " << *it1 << " *it2 = " << *it2 << " ref1 = " << ref1 << " ref2 = " << ref2 << endl;
    cout << "vec1.data = " << vec1.data() << " vec2 = " << vec2.data() << endl;
    cout << "swap after======" << endl;
    vec1.swap(vec2);
    for(int c: vec1)
    {
        cout << c << "\t";
    }
    cout << endl;

    for(int c: vec2)
    {
        cout << c << "\t";
    }
    cout << endl;
    cout << "vec1.size===" << vec1.size() << " vec1.capacity=" << vec1.capacity() << endl;
    cout << "vec2.size===" << vec2.size() << " vec2.capacity=" << vec2.capacity() << endl;
    cout << "*it1 = " << *it1 << " *it2 = " << *it2 << " ref1 = " << ref1 << " ref2 = " << ref2 << endl;
    cout << "vec1.data = " << vec1.data() << " vec2 = " << vec2.data() << endl;
    cout << endl;
}

int main()
{
    //int = [-2147483648, 2147483647]

    getElement();
    cout << endl;

    cout << "Hello World!" << endl;
    return 0;
}

运行结果:

两个容器交互后,不公元素交换了,空间大小也交换了(是交接了地址吗?swap交换原理,从结果上看,两个元素的首地址交换了,并没有重生分配空间)

注意,交换后迭代器与引用保持与原来的元素关联,例如it1指向的元素还是23,ref1引用的元素还23。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值