vector::operator==

在 Visual C++ 演示如何使用 向量:: operator== 标准 (STL)模板库函数。

template<class _TYPE, class _A> inline
   bool operator==(
   const vector<_TYPE, _A>& _X,
   const vector<_TYPE, _A>& _Y
);

备注

说明说明

类/参数名在原型不匹配版本在头文件。修改某些提高可读性。

此示例声明调用 ID 的用户定义类的三个空的向量,每个包含一个名称的字符串成员和分数整数成员。它创建 ID 三个矢量然后比较向量使用 operator== 由定义为 ID.

示例

// Opequal.cpp
// compile with: /EHsc
// Illustrates how to define the operator== to compare vectors.
//
// Functions:
//
//    vector::operator== - Vector equality comparison.
//    vector::push_back - Appends (inserts) an element to the end of a
//                        vector, allocating memory for it if necessary.
//
//////////////////////////////////////////////////////////////////////

// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is disabled.
#pragma warning(disable:4786)

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std ;
using namespace std::rel_ops ;

// The ID class is used for team scoring. It holds each player's name
// and score.
class ID
{
public:
    string Name;
    int Score;

    ID() : Name(""), Score(0) {}
    ID(string NewName, int NewScore) : Name(NewName), Score(NewScore) {}
};

// In this example, an ID is equivalent only if both name and score match.
bool operator==(const ID& x, const ID& y)
{
    return (x.Name == y.Name) && (x.Score == y.Score);
}

// IDs will be sorted by Score, not by Name.
bool operator<(const ID& x, const ID& y)
{
    return x.Score < y.Score;
}

// Define a template class for a vector of IDs.
typedef vector<ID> NAMEVECTOR;

int main()
{
    // Declare 3 dynamically allocated vectors of names.
    NAMEVECTOR Vector1, Vector2, Vector3;

    // Create 3 short vectors of names.
    Vector1.push_back(ID("Karen Palmer", 2));
    Vector1.push_back(ID("Ada Campbell", 1));

    Vector2.push_back(ID("John Woloschuk", 3));
    Vector2.push_back(ID("Grady Leno", 2));

    Vector3.push_back(ID("Karen Palmer", 2));
    Vector3.push_back(ID("Ada Campbell", 1));

    // Compare Vector1 to Vector2 and show whether they're equivalent.
    Vector1 == Vector2 ? cout << "Vector1 == Vector2"
                       : cout << "Vector1 != Vector2";
    cout << endl;

    // Compare Vector1 to Vector3 and show whether they're equivalent.
    Vector1 == Vector3 ? cout << "Vector1 == Vector3"
                       : cout << "Vector1 != Vector3";
    cout << endl;
}
  

要求

标题: vector

请参见

概念

标准模板库示例