Reputation: 928
I have the following 2D map that allows me to iterate through the outer map first then the inner map as shown below:
map<string, map<string, double>> grid;
for (map<string, map<string, double>>::iterator person = grid.begin(); person != grid.end(); ++person)
{
personTotal = 0;
for (map<string, double>::iterator product = person->second.begin(); product != person->second.end(); ++product)
{
personTotal += product->second;
}
personFunction(person->first, personTotal);
}
Now I would want to iterate through the inner map first then the outer map. However, I couldn't figure out how to do it. The following is a description of what I'm trying to achieve:
map<string, map<string, double>> grid;
for (??? product = ???; product ???; ++product)
{
productTotal = 0;
for (??? person = ???; person ???; ++person)
{
productTotal += grid[person->first][product->first];
}
productFunction(product->first, productTotal);
}
Is it possible to iterate the inner map first then the outer map? If not, I guess I need to change my data structure. What data structure would allow me to freely iterate in either dimension (with string as the key)?
Upvotes: 2
Views: 458
Reputation: 1528
A map of maps won't do the trick, because you can iterate over one dimension (let's call them the rows) but not over the other dimension (let's call them the columns).
The solution is to use an array-like structure (so you can iterate either on rows or on columns) where only the [row,column] points where you have data are used. This is generally called a sparse matrix.
You could use for example the Boost ublas mapped-matrix.
See this question for more alternatives: Is there a Boost (or other common lib) type for matrices with string keys?
Upvotes: 1