在两个std::向量之间匹配元素

match elements between two std::vectors

本文关键字:向量 之间 元素 std 两个      更新时间:2023-10-16

我正在编写一个估计光流的模块。在每个时间步长,它消耗一个std::向量,其中向量的每个元素都是当前像素位置和前一个像素位置。矢量未排序。以前未看到的新像素将出现,未找到的流位置将消失。是否有正确的方法将新矢量中的元素与正在估计的光流位置集相匹配?

矢量的数量级为2000个元素。

以下是我正在考虑的方法:

  • 天真地迭代每个估计光流位置的新矢量
  • 天真地迭代新的矢量,但删除每个匹配的位置,这样搜索就可以更快地进行
  • 在每个时间步对我的列表和新列表运行std::sort。然后从最后匹配的索引+1开始迭代新向量

我怀疑有一种公认的方法可以做到这一点,但我没有受过任何compsci培训。

如果相关的话,我在c++11中。

// each element in the new vector is an int. I need to check if 
// there are matches between the new vec and old vec
void Matcher::matchOpticalFlowNaive(std::vector<int> new_vec)
{
for(int i = 0; i < this->old_vec.size(); i++)
for(int j =0; j < new_vec.size(); j++)
if(this->old_vec[i] == new_vec[j]){
do_stuff(this->old_vec[i],  new_vec[j])
j = new_vec.size();
}
}

不确定你需要什么,但是,假设你的Matcher是用一个整数向量构建的,顺序不重要,并且当匹配时你需要用其他向量(方法matchOpticalFlowNaive())检查这个向量来做一些事情,我想你可以写如下

struct Matcher
{
std::set<int> oldSet;
Matcher (std::vector<int> const & oldVect)
: oldSet{oldVect.cbegin(), oldVect.cend()}
{ }
void matchOpticalFlowNaive (std::vector<int> const & newVec)
{
for ( auto const & vi : newVec )
{
if ( oldSet.cend() != oldSet.find(vi) )
/* do something */ ;
}
}
};

其中Matcher对象是用一个向量构造的,该向量用于初始化std::set(或std::multi_set,或无序集/多集?),以简化matchOpticalFlowNaive()中的工作