使用的迭代器在容器和算法中交互

在vector中查找元素及其位置
该程序是使用STL顺序容器std::vector(类似动态数组)来存储一些整数,在使用std::find算法在集合中查找该整数。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> vecIntegerArray;//声明一个整形的动态数组
    //向数组中添加整数,用push_back向动态数组中添加数据
    vecIntegerArray.push_back(50);
    vecIntegerArray.push_back(2991);
    vecIntegerArray.push_back(24);
    vecIntegerArray.push_back(9999);

    cout << "The contents of the vector are: " << endl;
    //iterator迭代器,声明了一个迭代器对象iArrayWalker,并将其初始化只想容器开头,即vector的成员函数begin()的返回值。
    vector<int>::iterator iArrayWalker = vecIntegerArray.begin();
  //auto iArrayWalker = vecIntegerArray.begin();可以使用关键字auto,让编译器确定类型
    while (iArrayWalker != vecIntegerArray.end()) {
        cout << *iArrayWalker << endl;//打印动态数组中的值
        ++iArrayWalker;//增加这个迭代器指向下一个元素
    }
    //使用find在vector中查找值
    vector<int>::iterator iElement = find(vecIntegerArray.begin(), vecIntegerArray.end(), 2991);
    if (iElement != vecIntegerArray.end()) {
        int Position = distance(vecIntegerArray.begin(), iElement);//用distance查找元素所处位置的偏移量
        cout << "value: " << *iElement << endl;
        cout << "found in the vector at position:" << Position << endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值