C++vector与list区别

//
//  main.cpp
//  C++Test25
//

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

// 1.vector数据结构
// vector和数组类似,拥有一段连续的内存空间,并且起始地址不变。
//因此能高效的进行随机存取,时间复杂度为o(1);
//但因为内存空间是连续的,所以在进行插入和删除操作时,会造成内存块的拷贝,时间复杂度为o(n)。
//另外,当数组中内存空间不够时,会重新申请一块内存空间并进行内存拷贝。
//
// 2.list数据结构
// list是由双向链表实现的,因此内存空间是不连续的。
//只能通过指针访问数据,所以list的随机存取非常没有效率,时间复杂度为o(n);
//但由于链表的特点,能高效地进行插入和删除。
//
// 3.vector和list的区别
//我们看一个简单的vector和list使用示例:

int main(int argc, const char *argv[]) {
    vector<int> v;
    list<int> l;
    for (int i = 0; i < 8; i++) 往v和l中分别添加元素
    {
        v.push_back(i);
        l.push_back(i);
    }
    cout << "v[2]=" << v[2] << endl;
    // cout<<"l[2]="<<l[2]<<endl;  //编译错误,list没有重载[]
    cout << (v.begin() < v.end()) << endl;
    // cout<<(l.begin()<l.end())<<endl; /编译错误,list::iterator没有重载<或>
    cout << *(v.begin() + 1) << endl;
    // cout<<*(l.begin()+1)<<endl; //编译错误,list::iterator没有重载+
    vector<int>::iterator itv = v.begin();
    list<int>::iterator itl = l.begin();
    itv = itv + 2;
    // itl=itl+2; //编译错误,list::iterator没有重载+
    itl++; // list::iterator中重载了++,只能使用++进行迭代访问。
    itl++;
    cout << *itv << endl;
    cout << *itl << endl;
  
    // vector中v[i]与v.at(i)的区别
    // 为了效率v[i]不进行数组越界检查,at[i]进行数组越界检查
    //    void f(vector<int> &v)
    //    {
    //        v[5];    // A
    //        v.at[5];  // B
    //    }
    getchar();
    return 0;
}
//vector拥有一段连续的内存空间,能很好的支持随机存取,
//因此vector<int>::iterator支持“+”,“+=”,“<”等操作符。
//
//list的内存空间可以是不连续,它不支持随机访问,
//因此list<int>::iterator则不支持“+”、“+=”、“<”等
//
//vector<int>::iterator和list<int>::iterator都重载了“++”运算符。
//
//总之,如果需要高效的随机存取,而不在乎插入和删除的效率,使用vector;
//如果需要大量的插入和删除,而不关心随机存取,则应使用list。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VCHH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值