【问题标题】:Assigning value to member of a map through an iterator通过迭代器为地图成员赋值
【发布时间】:2014-03-05 03:41:24
【问题描述】:

我正在尝试遍历地图并为其中的元素赋值:

typedef map<int,Node, less<int> >::const_iterator TopologyIter;

bool
RoutingManager::ActivateNewNode()
{
    TopologyIter iter;
    do
    {
        if(!iter->second.online)
        {
            iter->second.online = true;
            iter->second.connection = myConnection->newConnections.back();
            myConnection->newConnections.pop_back();
            return true; //all good
        }       

        iter++;

    }while (iter != topology.end());

    return false; //received a connection, but no more nodes to hand out
}

但是,我收到以下错误:

manager.cpp:91:24:错误:在只读对象中分配成员“Node::online” iter->second.online = true;

这是我的节点结构:

#pragma once

#include <map>
#include "nodecon.h"
typedef map<int,int, less<int> >::const_iterator NodeNeighborsIter;

struct Node
{
    int id;
    std::map<int,int> neighbors;
    bool online;

    struct NodeConnection connection;
};

我在这里错过了什么?

【问题讨论】:

  • 首先,iter 在您尝试取消引用之前未分配给任何东西
  • const_iterator 表示它指向的对象是const - 无法更改。

标签: c++ map iterator


【解决方案1】:

const_iterator 不能用于修改容器的内容。通过取消引用const_iterator 获得的所有值都是const

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2020-03-10
    • 2011-03-24
    • 2015-12-22
    • 1970-01-01
    相关资源
    最近更新 更多