练习3.34
假定p1和p2指向同一个数组中的元素,则下面程序的功能是什么?什么情况下该程序是非法的?
p1 += p2 -p2;
解答:
很多情况下,这段代码都会出错。
1. p2是last*,p1是begin*
2.p1的位置大于p2很多
练习3.35
编写一段程序,利用指针将数组中的元素置为0。
解答:
#include <iostream>
#include <iterator>
using namespace std;
int main(){
int num[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto first = begin(num);
auto last = end(num);
for (; first != last; ++first){
*first = 0;
}
for (auto i : num){
cout << i << endl;
}
}
练习3.36
编写一段程序,比较两个数组是否相等。在写一段程序,比较两个vector对象是否相等。
解答:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main(){
bool flag = true;
int num1[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int num2[11] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3 };
auto first1 = begin(num1);
auto last1 = end(num1);
auto first2 = begin(num2);
auto last2 = end(num2);
for (; first1 != last1 || first2 != last2; ++first1, ++first2){
if (*first1 != *first2){
flag = false;
break;
}
}
cout << flag << endl;
}
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main(){
bool flag = true;
int num1[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int num2[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 18, 9 };
auto first1 = begin(num1);
auto last1 = end(num1);
auto first2 = begin(num2);
auto last2 = end(num2);
vector<int> vnum1(first1, last1), vnum2(first2, last2);
cout << (vnum1 == vnum2) << endl;
}
这里vector对象可以直接进行比较。