c++ - 为二进制搜索排序对象 vector

标签 c++ vector map jquery-ui-sortable binary-search

我有以下类(class):

struct EdgeExtended {
    int neighborNodeId;
    int weight;
    int arrayPointer;
    bool isCrossEdge;

};

我想要一个这样的对象的 vector ,按 neighborNodeId 排序。然后我想搜索一个特定的 neighborNodeId 并通过二进制搜索返回对 vector 内找到的对象的引用。以前我为此使用了一张 map ,所以它是这样的:

map<int, EdgeExtended> neighbours;
.....

auto it = neighbours.find(dnodeId);
if (it != neighbours.end()) {
    edgeMap = it->second; 
}

代替

map<int, EdgeExtended> neighbours;

我想拥有

vector<EdgeExtended> neighbours;

并保留尽可能多的旧代码相同。

如果 vector 比 map 快,我想进行基准测试,因为我正在构建数千个 vector (或 map )并且每个 vector ( map )相对较小(约 10 个项目)。我不知道如何 a) 使对象可按 neighborNodeId 排序和 b) 如何使用二进制搜索来搜索类的特定成员 (neighborNodeId)。对不起,菜鸟问题。我指望你的帮助。

最佳答案

您需要一个自定义比较器函数,该函数采用两个 EdgeExtended 对象并比较您感兴趣的字段,您可以将其传递给 sortbinary_search 分别作为第三个或第四个参数。

可以使用 lambda 函数方便地完成:

auto Comp = [](const EdgeExtended& e1, const EdgeExtended& e2)
{
    return e1.neighborNodeId < e2.neighborNodeId;
};

如果您卡在 C++11 之前,请改用重载的 operator() 编写一个类:

struct Comp {
    bool operator()(const EdgeExtended& e1, const EdgeExtended& e2) const
    {
        return e1.neighborNodeId < e2.neighborNodeId;
    }
};

关于c++ - 为二进制搜索排序对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20615640/

相关文章:

C++ 浅拷贝和深拷贝 - 反射(reflect) vector 的 num_items 的变化

map - hadoop输出文件无法识别的字符

c++ - LLVM:如何将 IR 写入文件并运行它?

c# - 等于 c# 中的 c++ extern

c++ - 在不创建新子 vector 的情况下获取 vector 范围

c++ - 使用 boost 库构建失败

python - 将字典映射到向量以获得一组索引向量

c++ - 将字符串和数字读取到 vector C++

map - Hadoop-大数据作业提交时间

Clojure 中的映射和记录相等性