【C++ Primer 第五版】迭代器

1 迭代器介绍

与指针不同,迭代器不是取地址符,有迭代器的类型拥有返回迭代器的成员
迭代器拥有begin和end的成员,begin成员返回第一个元素,end成员返回最后一个元素的下一个位置,即不存在的尾后
如果容器没有元素,则begin和end返回是相同的
采用auto关键字,可以不在意迭代器的准确类型

*iter 返回迭代器所指元素的引用
iter->mem 解引用,获取成员,等价于(*iter).mem
++iter 指示容器下一个元素
–iter 指示容器上一个元素
iter == iter2 判断是否相等
iter != iter2 判断不等

迭代器示例

string s("some string");
if (s.begin() != s.end()){
    auto it = s.begin();
    *it = toupper(*it);
}

2 迭代器定义

vector<int>::iterator it; // 读写vector<int>的元素
string::iterator it2; // 读写string对象中的字符
vector<int>::const_ierator it3; // 只读元素不写
string::const_itrator it4;// 只读字符不写

使用迭代器,不能向迭代器添加元素

3 迭代器运算

迭代器递增运算令迭代器每次移动一个元素
迭代器支持加减运算,移动n个元素
迭代器可以用==和!=比较位置是否相同

二分搜索从有序序列中寻找某个给定的值,每次查找中间位置进行判断,如果不是则缩小范围继续查找
eg:从0-99中猜出给定数40,每次猜测会给出偏大、偏小或猜中的判断

int main()
{    
    int tar = 40;
    vector<int> vec;
    for (int i= 0; i<=99; i++){
        vec.push_back(i);
    }
    vector<int>::iterator L = vec.begin(), R = vec.end();
    while(L <= R){
        auto mid = L + (R - L)/2;
        if (*mid == tar){
            cout << "Get the target num! It is " << *mid << endl;
            break;
        }
        else if (*mid < tar){
            cout << *mid << " is less than the target num!" << endl;
            L = mid;
        }
        else{
            cout << *mid << " is larger than the target num!" << endl;
            R = mid;
        }
    }
    return 0;    
}

输出结果为:

50 is larger than the target num!
25 is less than the target num!
37 is less than the target num!
43 is larger than the target num!
Get the target num! It is 40

二分查找使用mid = L + (R - L)/2而非mid = (L + R)/2,是为了防止迭代器越界

4 练习

  • 练习3.22 编写一端程序,创建字符串text,然后改成大写字符,再进行输出
#include <iostream>
#include <string>
using namespace std;
int main()
{    
    string text = "hello world!";
    string::iterator it;
    for (it = text.begin(); it != text.end(); ++it){
        *it = toupper(*it);
        cout << *it;
    }
    cout << endl;
    return 0;
}
  • 练习3.23 编写一段程序,创建含有10个整数的vector对象,然后使用迭代器将所有元素的值变为原来的两倍,然后输出
#include <iostream>
#include <vector>
using namespace std;
int main()
{    
    vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
    vector<int>::iterator it;
    for (auto it = vec.begin(); it != vec.end(); ++it){
        *it = *it*2;
        cout << *it << ' ';
    }
    cout << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值