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)/;
while (mid != end && *mid != name) {
if (name < *mid) {
end = mid;
} else {
beg = mid + ;
}
mid = beg + (end - beg)/2;
}
if (*mid == name) {
cout << mid - svec.begin() << endl;
} else {
cout << "Not found!" << endl;
}
return ;
}

练习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() - ; ++it) {
cout << *it + *(it + ) << endl;
}
return ;
}

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() - ;
for( ; head <= tail; ++head, --tail) {
cout << *head + *tail << endl;
}
return ;
}

练习3.25

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

练习3.26

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

上一篇:【小玩意】time-passing-by clock


下一篇:客户端TortoiseSVN的安装及使用方法 (申明:来源于网络)