hashtable,无序映射迭代器用法

hashtable,unorderd_map iterator usage

本文关键字:迭代器 用法 映射 无序 hashtable      更新时间:2023-10-16

我希望熟悉unorderd_map的人能给我一个最好的问题答案。

我试图使用迭代器访问存储在无序映射上的值,但遇到了以下错误。

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

以下是我的代码示例:

#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;
}

因此,当编译时出现错误:

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

const_iterator允许您在不修改容器成员的情况下对容器成员进行迭代。

如果你想修改它们,你需要使用一个普通的iterator