'How to remove a column from a matrix defined as Vectors within a Map in C++?
I have a matrix defined in C++ using vectors within a map as the following:
typedef std::vector<double> MyVector;
typedef std::map<unsigned int,MyVector> MyMap;
The vectors have number of elements equal to the number of keys in the map. So, without counting the column holding the keys, the collection of vectors will represent n*n matrix. If I want to remove a row, then I can just use "map.erase(key)" to do that. However, I don't have a way to remove a specific column from this matrix.
Solution 1:[1]
This solution is to remove the row and corresponding column based on the map's key. It is not perfect and I wish if someone improve upon it.
MyMap a2d;
MyMapIterator itr;
double value=1;
for(int i=0;i<5;i++){
a2d[i].emplace_back(value);
a2d[i].emplace_back(value);
a2d[i].emplace_back(value);
a2d[i].emplace_back(value);
a2d[i].emplace_back(value);
value++;
}
//display the Array
for (itr=a2d.begin();itr!= a2d.end();itr++){
for (auto vitr=itr->second.begin();vitr!=itr->second.end();vitr++){
cout<<*vitr<<"\t";
}
cout<<endl;
}
cout<<endl;
double rowR=2; // the map's key which represent the index of the row to be removed
double columnR;
columnR=distance(a2d.begin(),a2d.find(rowR)); //the amount of increment should be added to the vector's iterator to remove the required column
a2d.erase(rowR); // removing the 3rd row
for (itr=a2d.begin();itr!= a2d.end();itr++){
auto &k=itr->second;
k.erase(k.begin()+columnR); // removing the 3rd column
}
// re-displaying the array after change
for (itr=a2d.begin();itr!= a2d.end();itr++){
for (auto vitr=itr->second.begin();vitr!=itr->second.end();vitr++){
cout<<*vitr<<"\t";
}
cout<<endl;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fady Samann |
