c++第十六天

p99~p101:

1、迭代器的指向:容器内的元素或者尾元素的下一位。


2、迭代器与整数相加减返回值为移动了若干位置的迭代器。

 

3、迭代器间相加减返回值则是类型为 difference_type 的带符号整数。

 

4、使用迭代器运算的一个经典算法是二分搜索。

 

(注:字典序实际是按照ASCII来排的,具体如下:

 

0-9(对应数值48-59);A-Z(对应数值65-90);a-z(对应数值97-122);因此,按照从小到大排序,大写总是排在前面

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<vector>
using std::vector;
#include<string>
using std::string;
int main()
{
    // 定义一个有序的vector<string>
    vector<string> svec{"Abigal", "Baey", "Candice",
    "DAISY", "EILEEN", "FREDERICA", "GINA"};
    // 输入要查找的名字
    string name;
    cin >> name;
    // 二分搜索
    auto beg = svec.begin(), end = svec.end();
    auto mid = svec.begin() + (end - beg)/2;
    while (mid != end && *mid != name) {
        if (name < *mid) {
            end = mid;
        } else {
            beg = mid + 1;
        }
        mid = beg + (end - beg)/2;
    }
    if (*mid == name) {
        cout << mid - svec.begin() << endl;
    } else {
        cout << "Not found!" << endl;
    }
    return 0;
}

 

 

练习3.24

1

#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<vector>
using std::vector;int main()
{
    int temp;
    vector<int> v;
    while(cin >> temp) {
        v.push_back(temp);
    }
    // 用迭代器遍历、访问元素
    for(auto it = v.cbegin();
        it != v.cend() - 1; ++it) {
        cout << *it + *(it + 1) << endl;
    }
    return 0;
}

2

#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<vector>
using std::vector;int main()
{
    int temp;
    vector<int> v;
    while(cin >> temp) {
        v.push_back(temp);
    }
    // 用迭代器遍历、访问元素
    auto head = v.cbegin();
    auto tail = v.cend() - 1;    
    for( ; head <= tail; ++head, --tail) {
        cout << *head + *tail << endl;
    }
    return 0;
}

 

练习3.25

#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<vector>
using std::vector;
int main()
{
    vector<unsigned> score(11, 0);
    unsigned grade;
    auto ind = score.begin();
    while (cin >> grade) {
        if (grade <= 100)
            ++*(ind + grade/10);
    }
    for (auto i: score) {
        cout << i << endl;
    }
    return 0;
}

 

练习3.26

迭代器间不支持加法运算。(参考99页)

posted @ 2017-02-15 10:56  xkfx  阅读(167)  评论(0编辑  收藏  举报