首页 > 解决方案 > 在 C++ 中对类对象向量起作用的函数

问题描述

我有一个Edge用 memeberspair<double,double> spair<double,double> e.

main函数中,我有一个边向量vector<Edge> edgesEdge我用对象填充它。

现在我想找到一个特定的索引Edge x。所以我写了一个函数:

int indexOf(vector<Edge>& arr,Edge& k);

函数体在这里无关紧要。现在我的问题是,如何使函数像这样工作:

edges.indexOf(x)

无需将边向量作为参数传递?

标签: c++functionclassvectoroverloading

解决方案


也许继承 std::vector?

#include <iostream>
#include <vector>

using namespace std;

struct Edge
{
    Edge(double _s, double _e) : s(_s), e(_e) {}
    double s;
    double e;
};

bool operator==(const Edge &lhs, const Edge &rhs) {
    return lhs.s == rhs.s && lhs.e == rhs.e;
}

class MyVector : public vector<Edge>
{
public:
    int index_of(const Edge &e)
    {
        for (int i = 0; i < this->size(); ++i) {
            if (this->at(i) == e)
                return i;
        }
        return -1;
    }
};

int main()
{
    MyVector v;
    for (int i = 0; i < 10; ++i)
        v.emplace_back(i, i);
    cout << v.index_of(v.at(5)) << endl;
    return 0;
}

推荐阅读