I am new to C++ and want to do vector element elimination.
My vectors are like:
<vector<vector>> objPoints;
<vector<vector>> delPoints;
<vector<vector>> objPoints2;
each objPoints has size 1000x3 and has all points. From objPoints i want to remove delPoints i.e. the (X,Y,Z) values that reside in each row.
Can anyone please tell me syntax?
You may consider read this Q&A on StackOverflow on how to erase elements from STL containers.
The key point is to use the erase-remove idiom to erase items from the vector, and use a lambda to express the erasing condition:
Full compilable code sample (live here):
Output:
One obivious method would be:
You can do it much more efficiently if you are allowed to sort the vectors. I will provide you with method and pseudo code then you can implement it on you own.
For comaprison, first compare w.r.t
x cordinate
theny
and thenz
. For sorting, you can usestd::sort
with same comparison function described in previous line. For deleting, you can usestd::vector::erase
.Or you can implement your own fuctions.
If you definately have to use vectors, an easy (but inefficient) way would be to
std::find
the element in objPoints that you want to remove and then remove it withstd::vector::erase
.I interpret your questions as follows: You have two vectors
objPoints
anddelPoints
which contain 1000 three-dimensional points. I would encode this asstd::vector<std::array<int,3> > objPoints;
where I assumed you have some raster such that you can desribe your points by
int
values (otherwise, fordouble
entries, comparison is not that easy).One benefit of using
std::array<int,3>
is that you automatically get a lexicographic ordering of the points (that means, specializations ofstd::less
andstd::equal_to
which can directly be used without the further need to create some).Algorithm:
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 ofO(size1 log(size1)) + O(size2 log(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)
.Implementation:
DEMO
All together, this requires an effort of
O(c1.size()) + O(c1.size() * log(c1.size())
(naturally assumingc1.size()>=c2.size()
).One can easily extend this to take an arbitrary comparison operator instead of the
operator==
.