user1701545
user1701545

Reputation: 6210

Map to a 2 dimensional vector

I want to create a C++ map where key is, say, int and value is a 2-D vector of double:

std::map<int, std::vector<vector<double>>> myMap;

suppose I filled it and now I would like to update the second vector mapped by each key (for example divide each element by 2). How would I access that vector iteratively? The "itr->second[0]" syntax in the statement below is obviously wrong. What would be the right syntax for that action?

for(std::map<in, vector<vector<double> > > itr = myMap.begin(); itr != myMap.end();++itr)
{
    for(int i = 0;i < itr->second[0].size();++i)
    {
         itr->second[0][i] /= 2;
    }
}

thanks, rubi

Upvotes: 3

Views: 3021

Answers (2)

DoubleA
DoubleA

Reputation: 33

I got a solution but a little bit different

  • used a 2d vector to insert values
  • copied that vector into the map
  • used another 2d vector to copy contents from the map and do the work
  • copied the modified vector back to the map
map<int,vector<vector<double>>> myMap;
vector<vector<double>>v;
v.push_back({7,8});
v.push_back({6,9,8});
myMap[0]=v;
for(auto i=myMap.begin();i!=myMap.end();i++)
{
   vector<vector<double>>v1=i->second;
   for(int j=0;j<v1.size();j++)
   {
      for(int k=0;k<v1[j].size();k++)v1[j][k]/=2;
   }
   i->second=v1;
}

p.s Ik I'm 8yrs late

Upvotes: 0

quetzalcoatl
quetzalcoatl

Reputation: 33556

itr->second is a type of vector<vector<double>>, so you have 'two levels' of indexes to iterate over before you can divide a cell by a number.

for ....
{
    vector<vector<double>>& vv = itr->second;
    for(int i=0; i<vv.size(); ++i)
        for(int j=0; j<vv[i].size(); ++j)
            vv[i][j] /= 2
}

did I understand your question correctly?

edit: after you edited your post, the code is almost correct. You have some typos and your iterator type is invalid, please see (the code below compiles at least in mingw)

std::map<int,std::vector<std::vector<double> > > myMap;

for(std::map<int, std::vector<std::vector<double> > >::iterator itr = myMap.begin();
    itr != myMap.end();
    ++itr)
{
    for(int i = 0;i < itr->second[0].size();++i)
    {
         itr->second[0][i] /= 2;
    }
}

please note the ::iterator added. It must not be ::const_iterator as the map is going to be modified

Upvotes: 4

Related Questions