C++ primer 第五版 中文版 9.2.7 节练习
练习 9.15:编写程序,判定两个vector是否相等。
答:
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
int main(void)
{
vector<int> a{1,2,3,4,5,6,7},b{1,2,3,4};
if(a==b)
cout<<"a和b相等"<<endl;
else
cout<<"a和b不相等"<<endl;
return 0;
}
练习 9.16:重写上一题的程序,比较一个list中元素和一个veotr中的元素。
答:
#include <iostream>
#include <vector>
#include <list>
using std::vector;
using std::list;
using std::cout;
using std::endl;
int main(void)
{
list<int> temp{1,2,3,4,5};
vector<int> temp2{1,2,3,5},ass;
ass.assign(temp.cbegin(),temp.cend());
if(ass==temp2)
cout<<"temp1和temp2相等"<<endl;
else
cout<<"temp1和temp2不相等"<<endl;
return 0;
}
练习9.17 假定c1和c2是两个容器,下面比较操作有何限制?
if(c1<c2)
答: 1、c1和c2容器类型和元素类型必须相同。
2、c1和c2的元素类型要定义了比较运算符才能比较。