我试过了:
#include <iostream>
#include <list>
#include <vector>
template<typename T, typename U>
bool is_equal(T begin_vec,T end_vec, U begin_list, U end_list){
while(begin_vec!=end_vec){
if(*begin_vec==*begin_list){
begin_vec++;
begin_list++;
return true;
}
else return false;
}
}
int main(){
std::vector<int> vec_num{1,2,3,4,5,6};
std::list<int> list_num{1,2,3,4,5,6};
if(is_equal(vec_num.begin(),vec_num.end(),list_num.begin(),list_num.end())){
std::cout<<"They are equal!"<<std::endl;
}
}
我认为,例如,如果一个向量的元素较少,并且在该点之前所有元素都相等,就会出现问题。
#include <iostream>
#include <list>
#include <vector>
#include <iterator>
template <typename T,typename U>
bool is_equal ( T beg1, T end1, U beg2, U end2 )
{
if(std::distance(beg1,end1)!=std::distance(beg2,end2)){
return false;
}
else{
while (beg1!=end1) {
if (!(*beg1 == *beg2)) {
return false;}
++beg1;
++beg2;
}
return true;
}
}
int main(){
std::vector<int> vec_num{1,2,3,4,5,6};
std::list<int> list_num{1,2,3,4,5,6};
if(is_equal(vec_num.begin(),vec_num.end(),list_num.begin(),list_num.end())){
std::cout<<"They are equal!"<<std::endl;
}
}