[英]Why am I unable to use push_back on this vector?
I am trying to create a graph.我正在尝试创建一个图表。 I am modelling the edges as a
std::pair
of the connected vertices and the weights of the edges connecting these vertices.我将边建模为
std::pair
连接的顶点和连接这些顶点的边的权重。 I am inserting this edge through another graph class which holds all these vertices as a std::set
.我通过另一个图 class 插入这条边,该图将所有这些顶点保存为
std::set
。
The way I am going about it is as follows:我打算这样做的方式如下:
Here's the vertex class:这是顶点 class:
class Vertex {
public:
friend std::ostream &operator<<(std::ostream &os, const Vertex &v);
Vertex(char c) : ID_(c) {}
bool operator==(const Vertex &rhs) const {
return (this->ID_ == rhs.ID_);
}
bool operator<(const Vertex &rhs) const {
return (this->ID_ < rhs.ID_);
}
char ID_;
std::vector<std::pair<Vertex, int>> neighbors;
};
Here's the graph class which holds the vertices:这是包含顶点的图 class:
class Graph {
public:
friend std::ostream &operator<<(std::ostream &os, const Graph &g);
Graph();
Graph(char c[]);
void insertVertex(char c);
void insertEdge(char ID1, char ID2, int weight);
protected:
std::set<Vertex> vertices_;
};
And here's my edge insertion method:这是我的边缘插入方法:
void Graph::insertEdge(char c1, char c2, int w) {
auto it1 = vertices_.find(c1);
auto it2 = vertices_.find(c2);
auto p1 = std::make_pair(*it1, w);
if(it1 != vertices_.end())
it1->neighbors.push_back(p1); // Fails here
}
Does the ->
operator return the object that the iterator points to, or does it return something like a const reference to it? ->
运算符是返回迭代器指向的 object,还是返回对它的 const 引用之类的东西?
I think I found the problem.我想我发现了问题。 std::set cant be modified, atleast not directly.
std::set 不能修改,至少不能直接修改。 To make its elements modifiable, I did something like this:
为了使其元素可修改,我做了这样的事情:
mutable std::vector<std::pair<Vertex, int>> neighbors;
Basically making the attribute of the element that I want to modify in the set mutable .基本上使我想在 set mutable中修改的元素的属性。
Thanks to this answer: https://stackoverflow.com/a/7340470/14635766感谢这个答案: https://stackoverflow.com/a/7340470/14635766
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.