I have coded this to remove similar vector from 2d vector, this can be for any numbers of vector inside 2d vector but for example I have taken only 3 vector.
here, {1,2,3,4}
is similar to {3,2,1,4}
so I have to remove {3,2,1,4}
.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<vector<int> > v = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 3, 2, 1, 4 } };
vector<int> r, c;
// sorting elements
for (auto row = v.begin(); row != v.end(); row++) {
sort(row->begin(), row->end());
}
// Deleting Duplicates
for (auto row = v.begin(); row != v.end() - 1; row++) {
r.clear();
c.clear();
cout << endl
<< endl;
for (auto col = row->begin(); col != row->end(); col++) {
r.push_back(*col);
}
for (auto cr = row + 1; cr != v.end(); cr++) {
for (auto cc = cr->begin(); cc != cr->end(); cc++) {
c.push_back(*cc);
}
if (r == c)
v.erase(cr->begin(), cr->end());
c.clear();
}
cout << endl;
}
// Printing
for (auto row = v.begin(); row != v.end(); row++) {
for (auto col = row->begin(); col != row->end(); col++) {
cout << *col << " ";
}
}
}
error: no matching function for call to ‘std::vector >::erase(std::vector::iterator, std::vector::iterator)'
You can easily sort your 2d vector's elements and then compare them one by one. Here, one function compares two 1d vectors and returns the result.
Note: When an element of your 2d vector gets deleted, the next element replaces it, so you shouldn't increase the target index (index k in my code). Increase the index only if these two elements are not equal.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool twoVectorsAreEqual(vector<int> first_vec, vector<int> second_vec) {
sort(first_vec.begin(), first_vec.end());
sort(second_vec.begin(), second_vec.end());
return (first_vec == second_vec);
}
int main(){
vector<vector<int>> double_vec /* = some velue*/;
for (int i = 0; i < double_vec.size() - 1; i++) {
for (int k = i + 1; k < double_vec.size();) {
if (twoVectorsAreEqual(double_vec[i], double_vec[k])) {
double_vec.erase(double_vec.begin() + k);
else
k++;
}
}
}