Teemu
Teemu

Reputation: 49

Adding iterator to a pointer

struct Region
{
    Name name_;
    std::vector<RegionID*> lower_regions_;
    RegionID *upper_region_;
    std::vector<StopID*> stop_id_;
};

struct Stop
{
    Name name_;
    Coord coord_;
    RegionID *region_id_;
};



std::unordered_map<StopID, Stop> stops_;
std::unordered_map<RegionID, Region> regions_;

Here are my map and struct which contain information about bus stops and different regions they are located.

bool Datastructures::add_stop_to_region(StopID id, RegionID parentid) {
    std::unordered_map<StopID, Stop>::iterator stop = stops_.find(id);
    if (stop == stops_.end()) {
        return false;
    }

    std::unordered_map<RegionID, Region>::iterator region = regions_.find(parentid);
    if (region == regions_.end()) {
        return false;
    }

    if (stop->second.region_id_ != NULL) {
        return false;
    }

    //error: nvalid conversion from ?const std::__cxx11::basic_string<char>* to RegionID* {aka std::__cxx11::basic_string<char>*?} [-fpermissive]
    stop->second.region_id_ = &region->first;

    //error: no matching function for call to push_back(const std::__cxx11::basic_string<char>*)
    region->second.stop_id_.push_back(&stop->first);
    return true;

}

I don't understand why i cant add the key from map to the pointer(The last 3 code lines). And i don't want to store the RegionID or StopID as a value to the struct because else i would need to search the key from map every time i need the value from the RegionID or StopID.

Upvotes: 0

Views: 65

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

In an unordered_map, the key is const. You can't change it. An iterator for an unordered map gives access to a particular (key, value) pair stored in the map. As such, the first value of the iterator is a const value. In both of your errors, you are attempting to store a pointer to this const value into a structure that holds non-const (modifiable) values.

You can fix the error by changing region_id_ to be a const RegionID * and stop_id_ to be a std::vector<const StopID*>, so that both are constant pointers, but this may cause problems later if you try to write thru these pointers.

Upvotes: 1

Related Questions