且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++删除向量的某些元素

更新时间:2023-11-10 08:00:58

我对您的问题解释如下:您有两个向量objPointsdelPoints,其中包含1000个三维点.我将其编码为

I interpret your questions as follows: You have two vectors objPoints and delPoints which contain 1000 three-dimensional points. I would encode this as

std::vector<std::array<int,3> > objPoints;

我假设您有一些栅格,以便可以通过int值来区分点(否则,对于double条目,比较不是那么容易).

where I assumed you have some raster such that you can desribe your points by int values (otherwise, for double entries, comparison is not that easy).

使用std::array<int,3>的一个好处是,您可以自动获得这些点的字典顺序(这意味着std::lessstd::equal_to的专业化可以直接使用,而无需进一步创建它们).

One benefit of using std::array<int,3> is that you automatically get a lexicographic ordering of the points (that means, specializations of std::less and std::equal_to which can directly be used without the further need to create some).

算法:

首先对数组进行排序.在某些算法中,这并不是真正必要的(请参阅@AshwaniDausodia的其他答案),但以下假设为前提.此外,通常通过使用排序向量,可以获得更好的性能(至少在big-O中:对于未排序的容器,该值大致为O(size1*size2),而对于以下算法,该值较低).首先进行排序需要O(size1 log(size1)) + O(size2 log(size2))

First sort your arrays. There might be algorithms where this is not really necessary (see the other answer by @AshwaniDausodia), but the following assumes it. Further, in general by using sorted vectors one can obtain a better performance (at least in the big-O: for unsorted containers, it is roughly O(size1*size2), whereas it is lower for the following algorithm). The sorting first requires an effort of O(size1 log(size1)) + O(size2 log(size2))

接下来,同时遍历两个数组,每次找到一个公共元素时,将其从向量之一中删除.在遍历排序数组时,总是可以只增加指向较小元素的迭代器,因此此步骤需要O(size1+size2).

Next, traverse both arrays at the same time and each time you find a common element delete it from one of the vectors. As you traverse sorted arrays, where you can always increase only the iterator pointing to the smaller element, this step takes O(size1+size2).

实施方式:

// deletes the elements from container c1 which are also present in c2
// requires sorted containers c1 and c2
//
template< class ContainerType1, class ContainerType2 >
void delete_common_elements(ContainerType1& c1, ContainerType2 const& c2 )
{
    for(auto it1=c1.begin(), it2=c2.begin()
       ; it1!=c1.end() && it2!=c2.end(); )
    {
        if(*it1==*it2)  // eventually change here if your points are not int's
                        // but are of floating-point type
        {
             it1 = c1.erase(it1);  //it1 is increased here
        }
        else
        {
             *it1<*it2 ? ++it1 : ++it2;
        }
    }
}   

演示

总而言之,这需要O(c1.size()) + O(c1.size() * log(c1.size())的努力(自然地假定c1.size()>=c2.size()).

All together, this requires an effort of O(c1.size()) + O(c1.size() * log(c1.size()) (naturally assuming c1.size()>=c2.size()).

一个人可以轻松地将其扩展为采用任意比较运算符,而不是operator==.

One can easily extend this to take an arbitrary comparison operator instead of the operator==.