在下面的C++代码中,我想使用模板函数来确定两个向量是否完全相同,但是,我总是从模板函数中得到错误.你能给我一些关于如何从模板函数返回布尔值的建议吗?(我的C++编译器是g ++ 4.6)
编辑:在pop_back p1 p2 p3 p4之后,结果现在与我的预期相匹配.
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
template<class T> bool areTheyMatched(shared_ptr<vector<T>> p1, shared_ptr<vector<T>> p2) {
if ((*p1).size() == (*p2).size()) {
cout << (*p1).size() << endl;
for (unsigned int i = 0; i < (*p1).size(); i++) {
if ((*p1)[i] != (*p2)[i]) {
cout << (*p1)[i] << " " << (*p2)[i] << endl;
return false;
}
}
} else {
return false;
}
cout << "All elements are exactly the same" << endl;
return true;
}
int main(int argc, char *argv[]) {
shared_ptr<vector<int>> p1(new vector<int>);
shared_ptr<vector<int>> p2(new vector<int>);
shared_ptr<vector<double>> p3(new vector<double>);
shared_ptr<vector<double>> p4(new vector<double>);
for (int i = 0; i < 10; i++)
(*p1).push_back(i);
for (int i = 0; i < 9; i++)
(*p2).push_back(i);
(*p2).push_back(11);
for (double i = 0.0; i < 9.9; i += 1.1)
(*p3).push_back(i);
for (double i = 0.0; i < 8.8; i += 1.1)
(*p4).push_back(i);
(*p4).push_back(11.0);
cout << "Case 1: " << areTheyMatched(p1, p2) << endl;
(*p1).pop_back();
(*p2).pop_back();
cout << "Case 2: " << areTheyMatched(p1, p2) << endl;
cout << "Case 3: " << areTheyMatched(p3, p4) << endl;
(*p3).pop_back();
(*p4).pop_back();
cout << "Case 4: " << areTheyMatched(p3, p4) << endl;
p1.reset();
p2.reset();
p3.reset();
p4.reset();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1207 次 |
| 最近记录: |