1

I hope someone familiar with unorderd_map can give me a best answer to my problem.

am trying to access a values stored on an unorderd_map using iterator,but am stuck with the following error.

error: assignment of data-member ‘mystruct::time_diff’ in read-only structure

The following is sample of my code:

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
struct mystruct
{
     string str_name;
     time_t my_last_time;
     int time_diff;
};

int main()
{
    unordered_map<int,mystruct>hash_table;
    //filling my hash table
    for(int i=0;i<10;i++)
    {
      mystruct myst;
      myst.str_name="my string";
      myst.my_last_time=time(0);
      myst.time_diff=0;
      hash_table.insert(make_pair(i,myst));
    }
   //now, i want to access values of my hash_table with iterator.
   unordered_map<int,mystruct>::const_iterator itr=hash_table.begin();

  for (itr = hash_table.begin(); itr != hash_table.end(); itr++ )
  {
     time_t now=time(0);//pick current time 
     itr->second.time_diff=now-itr->second.my_last_time;//here is where my  error comes from
  }
  return 0;
}

so, when compile get an error:

error: assignment of data-member ‘mystruct::time_diff’ in read-only structure

1 Answer 1

3

A const_iterator lets you iterate over the members of a container without being able to modify them.

If you want to be able to modify them you need to use a plain iterator instead.

2
  • That is perfect, DONE!! Thanks. Nov 14, 2015 at 15:38
  • also if you have c++11 you can use jaus "auto it = ..."
    – Nick
    Nov 14, 2015 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.