【问题标题】:Unable to make a vector of pointers无法制作指针向量
【发布时间】:2013-09-02 01:07:31
【问题描述】:

在过去的两三个小时里,我一直在努力解决这个问题,但没有任何运气。我正在阅读文本,然后尝试创建一个邻接列表,其中所有顶点都具有指向列表中相邻顶点的链接。顶点类如下所示:

class Vertex {
private:
  std::vector<Vertex*> connPtrVertices;  // vector of vertices adjacent to this one
public:
  void addVertex(Vertex* vert) { connPtrVertices.push_back(vert); }

在 main.cpp 中,我试图像这样将顶点相互连接起来:

Vertex *v1, *v2;
v2->addVertex(v1);    // connect v2 to v1 
v1->addVertex(v2);    // connect v1 to v2 

我收到一条 Debug Assertion Failed 消息:

Debug Assertion Failed!

Program: C:\Windows\system32\MSVCP110D.dll
File: c:\program files (x86)\microsoft visual studio 11.0\vc\include\vector
Line: 240

Expression: vector iterators incompatible

我不知道该怎么做,任何帮助将不胜感激。

编辑: 第一次通过循环,我将 v1 和 v2 分配给 new,但第二次我检查它们是否存在,如果存在,我将指针分配给 Vertex,如下所示:

v1 = &(p_graph->getVertex(vert1));

调用的方法是这样的:

Vertex Graph::getVertex(std::string v) {         // gets the vertex 
  for (std::vector<Vertex>::iterator it = vertices.begin(); it != vertices.end(); it++) {
     if ((it->getName()).compare(v) == 0)
        return *it;  // if strings are the same return vertex
    }
    exit(1);
 }

这是错误的地方吗?

【问题讨论】:

  • 你从未初始化 Vertex v1 或 v2。
  • 学习使用你的调试器,请贴出相关代码。
  • 您发布的代码不完整(也不是最小的,也不是自洽的),我们不知道第240行是什么,所以无法判断问题是否是@ 987654327@ 不是真正的vector&lt;Vertex&gt;,或者完全不是别的东西。当你提出问题时,准备一个minimal complete example,当你编写代码时,从简单到复杂,慢慢构建,每一步都测试。

标签: c++ visual-studio-2010 pointers vector iterator


【解决方案1】:
  • 看来您只是想编译这段代码。现在,如果您构建项目,它会在没有编译器错误的情况下构建吗?调试呢?你可以试试,“不调试就开始”。这将在不调试的情况下执行您的代码。
  • 您收到的错误消息是:“向量迭代器不兼容”
  • 此错误来自您编写迭代器的位置,它似乎在 Graph::getVertex(std::string v) 函数中。要确认是这个函数,可以注释掉整个 Graph::getVertex(std::string v) 函数定义,看看错误是否消失。
  • 要修复迭代器错误“不兼容类型”,您可以使用 typedef 声明迭代器,如下所示:
  • typedef std::vector "" VertexType;
  • VertexType 顶点;

  • 顶点图::getVertex(std::string v) {

  • VertexType::iterator it;
  • for (it = vertices.begin(); it != vertices.end(); ++it){
  • 返回*它;
  • }
  • 退出(1);
  • }

  • 确保您的迭代器指向 Vertex 对象类型。

【讨论】:

    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2017-06-12
    • 2012-07-19
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多