这两种比较STL向量的方法有什么区别?



网上很少有例子使用相等运算符来比较两个STL vector对象的内容,以验证它们具有相同的内容。

vector<T> v1;
// add some elements to v1
vector<T> v2;
// add some elements to v2
if (v1 == v2) cout << "v1 and v2 have the same content" << endl;
else cout << "v1 and v2 are different" << endl;

相反,我阅读了使用std::equal()函数的其他示例。

bool compare_vector(const vector<T>& v1, const vector<T>& v2)
{
    return v1.size() == v2.size()
           && std::equal(v1.begin(), v1.end(), v2.begin());
}

这两种比较STL向量的方法有什么区别?

两者的行为方式完全相同。容器需求(表96)说明a == b具有操作语义:

distance(a.begin(), a.end()) == distance(b.begin(), b.end()) &&
equal(a.begin(), a.end(), b.begin())

问得好。我怀疑人们不使用==是因为他们不知道它在那里,但它确实做了手工编码版本所做的事情。它一直存在于序列容器和关联容器中。

最新更新