The first one thinks that it stands out that you implement your own functionality to search for an element: what is std::find . So, instead of:
bool alreadyPresent = false; int i = 0; for(i=0; i<SparseMatrix.size(); i++) { if((SparseMatrix[i].x == x) && (SparseMatrix[i].y == y)) { alreadyPresent = true; break; } }
You must write:
auto it = std::find(SparseMatrix.begin(), SparseMatrix().end(), Comparer);
where Comparer is a function that compares two SparseMatNode .
But the main improvement will be achieved through the use of an appropriate container. Instead of std::vector you would be much better off using an associative container. Thus, element search will have O(logN) complexity instead of O(N) . You can slightly modify your SparseMatNode class as follows:
typedef std::pair<int, int> Coords; typedef std::pair<const Coords, float> SparseMatNode;
You can cover these typedefs inside the class to provide a better interface, of course.
And then:
std::unordered_map<Coords, float> SparseMatrix;
This method can be used:
auto it = SparseMatrix.find(std::make_pair(x, y));
to find items much more efficiently.
source share