为什么unordered_set的迭代器是只读的?

时间:2016-08-26 18:25:28

标签: c++ const-iterator

#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_set>


using namespace std;
struct Car {
    int plate;
    int fuel = 0;
    Car(int plate) : plate(plate) { }

    inline bool operator==(const Car& car) const {
        return car.plate== this->plate;
    }
};

namespace std{
template<>
struct hash<Car> {
    size_t operator()(const Car& x) const {
        return x.plate;
    }
};
}

int main(){
    unordered_set<Car> cars;
    Car c1(123);
    cars.insert(c1);
    auto it = cars.begin();
    while (it != cars.end()){
        // ERROR: assignment of member 'Car::fuel' in read-only object
        it->fuel = 1;
        ++it;
    }
    return 0;
}

在上面的例子中,我该如何改变汽车的燃油?使用vector不会引发此问题。

0 个答案:

没有答案