C++ vector和iterator简单用法(转)

转自:https://blog.csdn.net/qq_38786209/article/details/80303190

vector是动态可变数组,可以添加int、double、自定义的类

1.int示例:

#incldue<vector>
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
for(vector<int>::iterator iter = a.begin();iter != a.end(); ++iter)
{
    cout << *iter << endl;
}

for(int i=0;i<a.size();i++)
{
    cout << a[i]<<endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

使用iterator和使用下标效果是一样的。

2.基本数据类型

使用对象名取地址,加入vector中

 vector<string*> a;
 string str = "hello";
 a.push_back(&str);
  • 1
  • 2
  • 3

3.自定义类

上面的方法有个弊端,就是必须写不同的对象名,才能区分对象。如果想要在循环里不断新建和消除对象,就不方便。

解决方法: 
假设我们有个类叫test_class,想要每次新建一个类,构造函数参数分别为x,y,并加入叫a的vector里

vector<test_class *> a;//该类的指针

test_class *tes = NULL;//声明一个test_class类型的指针
tes = new test_class(x,y);//申请一块新的内存空间,并初始化该对象,指针指向该对象
a.push_back(tes);

//在用到该对象时,应该使用指针的->,而不是用对象名.
tes->x;//✔
tes.x//✖
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值