如何在向量中插入唯一项? [英] How to insert unique items into vector?

查看:100
本文介绍了如何在向量中插入唯一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做 Neighbors 的类型:

typedef vector<pair<data,int>> Neighbors;

这是数据

struct data
{
    int par[PARAMETERS];
    int cluster;
    bool visited;
    bool noise;
};

我正在尝试编写一个函数,该函数插入 _NeighborPts中的值 NeighborPts (但只有尚未在 NeighborPts 中的那些):

I'm trying to write a function that inserts values from _NeighborPts to NeighborPts (but only ones that aren't already in NeighborPts):

void insert_unique(Neighbors* NeighborPts, const Neighbors& _NeighborPts)
{
    Neighbors_const_it _it = _NeighborPts.begin();
    while(_it != _NeighborPts.end())
    {
        if(/* _it->first.par isn't in *NeighborPts */)
            NeighborPts->push_back(*_it);
        ++_it;
    }
}

并且我已经有一个函数 equal()检查两个 par 是否相等。

and i already have a function equal() which checks if 2 pars are equal.

我必须在while循环中遍历 NeighborPts 并检查是否找到了该项目?还是我可以使用一些内置的 find find_if 函数为我做到这一点?

So do i have to iterate through NeighborPts in a while loop and check if the item is found? or could i use some built-in find or find_if function to do that for me?

推荐答案

您可以维护排序的向量。每次使用C ++算法中的 lower_bound 函数来定位插入位置。如果插入位置上的元素等于插入元素,则您有一个副本。

You can maintain a sorted vector. Use the lower_bound function from C++ algorithms to locate the insert position each time. If the element at the insert position is equal to the insert element then you have a duplicate.

除非矢量变得太大,否则这样做的效果会很好。最好使用集合或unordered_set的时间点有所不同,您需要进行基准测试才能找到它。

The performance of this will be pretty good unless the vector grows too large. The point at which you're better off using a set or a unordered_set varies and you'd need to benchmark to find it.

这篇关于如何在向量中插入唯一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆