1

我有一个名为 street_map 的类,其中包含一个带有 int 键和 type 值的地图vector<edge>。在其中一种方法中,我试图初始化一个指向该vector<edge>值的指针以获取其内容。

class street_map {
public:
    explicit street_map (const std::string &filename);
    bool geocode(const std::string &address, int &u, int &v, float &pos) const;
    bool route3(int source, int target, float &distance) const {
        auto it = adjacencyList.find(source);
        vector<edge>* v = &(it->second);
        return true;
    }
private:
    unordered_map<side , vector<segment>> map;
    unordered_map<int, vector<edge>> adjacencyList;
};

该行vector<edge>* v = &(it->second);给出了错误:

Cannot initialize a variable of type 'vector<edge> *' with an rvalue of type 'const std::__1::vector<edge, std::__1::allocator<edge> > *'

这是边缘类:

class edge {
    int node;
    string street;
    float length;
    int startingNode;
public:
    edge(int startingNode, int node, string street, float length) {
        startingNode = startingNode;
        node = node;
        street = street;
        length = length;
    }
};

我想知道这是否是因为 const 关键字以及如果是因为 const 关键字如何解决这个问题(我应该保留 const 关键字,但我想如果没有其他解决方案我可以摆脱它)。

4

1 回答 1

4

您有四个选择:

1) 使指针指向向量 const

您将无法修改矢量。

bool route3(int source, int target, float &distance) const {
        auto it = adjacencyList.find(source);
        const vector<edge>* v = &(it->second);
        return true;
    }

2)使您的 adjacencyList 可变

mutable 意味着可以从 const 函数作为非 const 访问 - 如果您不注意访问设计,这可能会有风险!

private:
    unordered_map<side , vector<segment>> map;
    mutable unordered_map<int, vector<edge>> adjacencyList;

3) 复制向量

这可能会带来更大的开销,并且对矢量所做的更改不会存储在您的地图中。

vector<edge> v = (it->second);

4)使函数非常量

请注意,这种方式不能在street_mapconst 的上下文中调用函数!

bool route3(int source, int target, float &distance) {
        auto it = adjacencyList.find(source);
        vector<edge>* v = &(it->second);
        return true;
    }
于 2015-12-01T16:47:18.967 回答