【发布时间】:2015-12-01 16:31:12
【问题描述】:
我有一个名为 street_map 的类,它包含一个带有 vector<edge> 类型的 int 键和值的映射。在其中一种方法中,我试图初始化一个指向 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 关键字,但我想如果没有其他关键字我可以摆脱它解决方案)。
【问题讨论】:
-
it很可能是一个 const_iterator。所以你要么需要一个非常量迭代器,要么必须将你的向量分配给一个 const 指针。 -
route3是一个 const 成员函数 =>adjacencyList是其中的 const =>find返回一个 const_iterator。 -
const vector<edge>* v = &(it->second);在您的应用程序中是否可接受?
标签: c++ pointers dictionary constants object-composition