c++ - 在 C++ 中对类对象向量起作用的函数
问题描述
我有一个Edge
用 memeberspair<double,double> s
和pair<double,double> e
.
在main
函数中,我有一个边向量vector<Edge> edges
。Edge
我用对象填充它。
现在我想找到一个特定的索引Edge x
。所以我写了一个函数:
int indexOf(vector<Edge>& arr,Edge& k);
函数体在这里无关紧要。现在我的问题是,如何使函数像这样工作:
edges.indexOf(x)
无需将边向量作为参数传递?
解决方案
也许继承 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;
}
推荐阅读
- ios - 使用条带实现 APPLE PAY
- swift - 从 Firebase 获取值并将其附加到 Swift 中的数组?
- scala - 写入 CosmosDB 集合时,数据框列不保持顺序,并且具有空值的列被排除在外
- html - NodeJs 尝试评估 HTML 表单
- python - 调试 Pycharm 'python_implementation' 时出错
- php - 无需重新加载页面即可保存数据
- angular - RXJS 组合了一个可观察的表
- excel - 使用 VBA 和 Outlook 向每位经理发送一份报告
- bson - BSON 文件到熊猫数据框
- html-table - 在 Thymeleaf 中迭代创建 AND