如何插入唯一的项目到向量
How to insert unique items into vector?
我有一个类型叫Neighbors
:
typedef vector<pair<data,int>> Neighbors;
这是data
:
struct data
{
int par[PARAMETERS];
int cluster;
bool visited;
bool noise;
};
我试图写一个函数,插入值从_NeighborPts
到NeighborPts
(但只有那些还没有在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;
}
}
和i已经有一个函数equal()
,它检查两个par
s是否相等。
所以我必须在while循环中迭代NeighborPts
并检查是否找到该项目?或者我可以使用一些内置的find
或find_if
功能来为我做到这一点吗?
您可以维护一个排序的向量。每次使用c++算法中的lower_bound
函数来定位插入位置。如果插入位置的元素等于插入元素,则存在重复元素。
这种方法的性能将非常好,除非向量变得太大。您最好使用set或unordered_set的点是不同的,您需要通过基准测试来找到它。
您当前的vector解决方案将在O(N^2)时间内运行,这是不高效的。对于高效的解决方案,一个关联容器将是很好的——比如std::set。此外,您还需要一些"operator less"(而不是"equal()")来传递给函数。
template < class T, // set::key_type/value_type
class Compare = less<T>, // set::key_compare/value_compare
class Alloc = allocator<T> // set::allocator_type
> class set;
所以你需要提供compare class
struct data_compare {
bool operator() (const data& lhs, const data& rhs) const{
//...
}
};
set<int64_t, data_compare> exising_items;
您可以定义这样的函数,或者在struct data中重写"operator <"
将"_NeighborPts"中的所有"data"插入到O(N*log(N)) time集合中
std::设置other_items;在循环中迭代_NeighborPts并插入数据元素
other_items.insert (_NeighborPts [i]);
std::设置my_items;在循环中迭代_NeighborPts并插入数据元素
my_items.insert (NeighborPts [i]);
现在你需要比较这两个集合:你可以用std::set_intersection来做. 或者对集合"my_items"构造一个简单的循环如果other_items中的当前元素不在_my_items中,则将其插入"NeighborPts"
此解决方案将运行在O(Nlog(N)) time
- 在
_NeighborPts
中没有绕过迭代项目。 - 只要你正在使用
std::vector
,没有绕过检查,以确定一个项目是否在NeighborPts
插入之前。
通过使用std::for_each
和函子,可以使代码更容易阅读。
struct UniqueItemInserter
{
UniqueItemInserter(Neighbors* neighborsIn) : neighbors(neighborsIn) {}
void operator(pair<data,int> const& item)
{
if ( std::find(neighbors->begin(), neighbors->end(), item) != neighbors->end() )
{
neighbors->push_back(item);
}
}
Neighbors* neighbors;
};
void insert_unique(Neighbors* NeighborPts, const Neighbors& _NeighborPts)
{
std::for_each(_NeighborPts.begin(), _NeighborPts.end(), UniqueItemInserter(NeighborPts));
}
- 如何有效地操作满足给定谓词的向量中的所有项目?
- 从加密项目向量中解密任意选择的元素会导致无效的 PKCS #7 块错误
- 如何使用擦除和迭代器来删除二维向量中的项目
- 有没有一种简单的方法可以在C++中获取特定索引之后向量中的所有项目?
- 为什么与<运算符的向量比较会比较每个项目两次?
- 如何将项目放入具有模板化超类类型的向量中
- 有没有更好的方法来检测向量中一个项目的多次出现?
- 总结向量v中的所有项目
- 在包含相同项目的向量中删除一个项目
- 防止向量项目被移动
- 向量中的项目的指针不稳定
- 将矢量中的项目与向量中的所有项目进行比较
- 如何从C 中的对象向量中删除一个项目
- 使用STD ::查找从向量中选择项目
- 将文件读取为由类项目组成的向量
- 检查项目是否已在向量中
- 在给定键 (C++) 的地图向量内查找项目
- 如何在助推向量中查找项目
- 在向量中插入 2 个项目
- 使用 push_back() 在向量中添加项目,向量的大小会增加但无法从向量中读取值