hashtable,unorderd_map迭代器用法

时间:2015-11-14 15:24:33

标签: c++ linux hashtable unordered-map

我希望熟悉unorderd_map的人可以为我的问题提供最佳答案。

我正在尝试使用迭代器访问存储在unorderd_map上的值,但是我遇到了以下错误。

window.onload = function() {

    function randomPath(){
    var x = Math.trunc(Math.random());
    var y = Math.trunc(Math.random());
    var xstep = 0;
    var ystep = 0;
    var path = '0,0';
    for (k = 0; k < 3 ; k++) {
          path += ' ';
          path += (x).toString();
          path += ',';
          path += (y).toString();
          xstep = Math.random();
          ystep = Math.random();
          xstep *= 10;
          ystep *= 10;
          x += Math.trunc(xstep);
          y += Math.trunc(ystep);
        }
        return path;
      }

    var figure = document.createElementNS('http://www.w3.org/2000/svg','svg');
    figure.id = 'brownian-figure';
    figure.setAttribute('height', '400pt');
    figure.setAttribute('width', '200pt');

    var pathArray = [];
    for (j = 0; j < 3; j++){
    pathArray[j] = document.createElementNS('http://www.w3.org/2000/svg','polyline');
    }

    for (i = 0; i < 3; i++){
    var path = randomPath();
    alert(path);
    pathArray[i].setAttribute('points', path);
    pathArray[i].setAttribute('style', 'fill:none;stroke:rgba(0,0,0,1);stroke-width:1');
    figure.appendChild(pathArray[i]);
    }

    var divfigure = document.createElement('div');
    divfigure.id = 'divfigure';
    divfigure.style = 'margin:0pt;padding:0pt;border:0pt none;background-color:rgba(240,240,240,1);position:absolute;top:100pt;left:100pt;width:200pt;height:400pt;';
    divfigure.appendChild(figure);

    document.body.appendChild(divfigure);
  };

以下是我的代码示例:

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

1 个答案:

答案 0 :(得分:3)

const_iterator允许您迭代容器的成员而无法修改它们。

如果您希望能够修改它们,则需要使用普通的iterator