C++ 我对常数、常数引用、常数引用感到困惑。。。(包括示例代码)
我正在尝试编写一个我感到满意的图形数据结构实现。(将邻接列表维护为集合而不是链表。)总之,我尝试使用引用和迭代器,并编写了以下内容:C++ 我对常数、常数引用、常数引用感到困惑。。。(包括示例代码),c++,reference,iterator,constants,C++,Reference,Iterator,Constants,我正在尝试编写一个我感到满意的图形数据结构实现。(将邻接列表维护为集合而不是链表。)总之,我尝试使用引用和迭代器,并编写了以下内容: #include <iostream> #include <string> #include <set> #include <stack> class Vertex { std::string name; std::set<Vertex> edges; public: Verte
#include <iostream>
#include <string>
#include <set>
#include <stack>
class Vertex {
std::string name;
std::set<Vertex> edges;
public:
Vertex(std::string name) : name(name) {}
std::string vertexName() const {
return name;
}
std::set<Vertex> outEdges() const {
return edges;
}
void addEdge(const Vertex& other) {
edges.insert(other);
}
void removeEdge(const Vertex& other) {
edges.erase(other);
}
int outDegree() {
return edges.size();
}
};
bool operator<(const Vertex& v1, const Vertex& v2) {
return (v1.vertexName().compare(v2.vertexName()) < 0);
}
void DFS(const Vertex& v) {
std::stack<Vertex*> stack;
std::set<Vertex*> visited;
stack.push(&v); // error1
visited.insert(&v); // error2
while (!stack.empty()) {
Vertex* vert_ptr = stack.top();
stack.pop();
std::cout << vert_ptr->vertexName() << std::endl;
//
for (std::set<Vertex>::iterator iter = vert_ptr->outEdges().begin(); iter != vert_ptr->outEdges().end(); iter++) {
if (visited.find(&(*iter)) != visited.end()) { // error3
stack.push(&(*iter)); // error4
visited.insert(&(*iter)); // error5
}
}
}
}
int main() {
Vertex a = Vertex("a");
Vertex b = Vertex("b");
Vertex c = Vertex("c");
DFS(a);
getchar();
return 0;
}
#包括
#包括
#包括
#包括
类顶点{
std::字符串名;
设置边;
公众:
顶点(std::string name):名称(name){}
std::string vertexName()常量{
返回名称;
}
std::set outEdges()常量{
返回边;
}
void addEdge(常量顶点和其他){
边缘。插入(其他);
}
void removedge(常量顶点和其他){
边缘。擦除(其他);
}
int-outDegree(){
返回边。size();
}
};
布尔运算符outeges().end();iter++){
if(visted.find(&(*iter))!=visted.end()){//error3
stack.push(&(*iter));//错误4
已访问。插入(&(*iter));//错误5
}
}
}
}
int main(){
顶点a=顶点(“a”);
顶点b=顶点(“b”);
顶点c=顶点(“c”);
外勤部(a);
getchar();
返回0;
}
我收到以下错误:
error1:E0304重载函数“std::stack::push[with _Ty=Vertex*,_Container=std::deque]”的实例与参数列表不匹配
error2:E0304重载函数“std::set::insert[with _Kty=Vertex*,_Pr=std::less,_Alloc=std::allocator]”的实例与参数列表不匹配
error3:E0304重载函数“std::set::find[with _Kty=Vertex*,_Pr=std::less,_Alloc=std::allocator]”的实例与参数列表不匹配
error4:E0304重载函数“std::stack::push[with _Ty=Vertex*,_Container=std::deque]”的实例与参数列表不匹配
error5:E0304重载函数“std::set::insert[with _Kty=Vertex*,_Pr=std::less,_Alloc=std::allocator]”的实例与参数列表不匹配
&
获取迭代器所指向的实际对象的地址,不知道我是否误解了迭代器的工作方式,或者这只是引用的问题
如果有人能为我提供一份关于这一切的好的参考资料,我将不胜感激(在您的例子中
void DFS(const Vertex&v)
v
是对常量变量的引用。换句话说,您承诺函数不会修改对象
std::stack<Vertex*> stack;
std::set<Vertex*> visited;
因此,您需要声明带有指向常量指针的容器:
std::stack<const Vertex*> stack;
std::set<const Vertex*> visited;
std::stack;
std::访问的集合;
现在,访问的find(&(*iter))
与set::iterator的实现有关。显然,运算符“*”返回的值引用了一个常量值,导致另一次从“const”到非const的转换尝试
这样,声明堆栈并用
std::stack<const Vertex*> stack;
std::set<const Vertex*> visited;