vector <bool>迭代器不可解除引用

use*_*856 2 c++ vector

我在编写它之后尝试调试我的程序,我遇到了这个错误:

在此输入图像描述

这是我的代码:

#include<fstream>
#include <iostream>
#include <vector>
#include <string>
#define MAXINT 2147483647

using namespace std;

struct Edge
{
int id, weight;

Edge(int y, int w)
{
    id = y;
    weight = w;
}
};

struct Node
{
vector <Edge *> Edges;
};

struct Graph
{
vector < Node *> vertices;
vector < int > indices;

void Resize(int x)
{
    if (vertices.capacity() < x)
        vertices.resize(x);
}

void InsertEdge(int x, int y, int weight)
{
    Resize(((x > y) ? x : y) + 1);
    InsertVertex(x);
    InsertVertex(y);
    vertices[x]->Edges.push_back(new Edge(y, weight));
}

void InsertVertex(int x)
{
    if (vertices[x] == NULL)
    {
        Node *t = new Node;
        vertices[x] = t;
        indices.push_back(x);
    }
}
};



void Dij(Graph const &g, int start)
{
Node *temp;
vector<bool> check;
vector<int>  distance, prev;
int v, w, weight, dist;

for (int i = 0; i <= g.indices.size(); i++)
{
    check.push_back(false);
    distance.push_back(MAXINT);
    prev.push_back(-1);
}

v = start;
distance[v] = 0;

while (!check[v])
{
    check[v] = true;
    temp = g.vertices[v];


    for (int i = 0; i < temp->Edges.size(); i++)
    {
        w = temp->Edges[i]->id;
        weight = temp->Edges[i]->weight;

        if (distance[w] > (distance[v] + weight))
        {
            distance[w] = distance[v] + weight;
            prev[w] = v;
        }
    }

    v = 1;
    dist = MAXINT;

    for (int x = 0; x < g.indices.size(); x++)
    {
        int i = g.indices[x];

        if (!check[i] && dist > distance[i])
        {
            dist = distance[i];
            v = i;
        }
    }
}
}

int main()
{
int startNode, nodeOne, nodeTwo, number;
Graph g;
ifstream myReadFile;
myReadFile.open("P:\\Documents\\New Folder\\Test\\src\\Read.txt");
while (!myReadFile.eof()) 
{
    myReadFile >> nodeOne;
    myReadFile >> nodeTwo;
    myReadFile >> number;
    g.InsertEdge(nodeOne, nodeTwo, number);
}

cout<< "Enter the starting node: ";
cin >> startNode;

Dij(g, startNode);

return 0;
}
Run Code Online (Sandbox Code Playgroud)

我为恼人的格式= /道歉.它在dij方法的最后一个for循环期间中断.有人知道我可能会省略什么吗?

yiz*_*lez 8

帕迪是对的!

但作为建议,不要使用vector<bool>......

看,C++众神想要创建一个节省空间的存储结构来存储bools.为了节省空间,他们使用了bits.因为bitsC++中没有单位:他们被迫使用chars.但是一个字符是8位!! C++众神提出了一个独特的解决方案:他们制作了一个特殊的成员类型:reference访问bools.您无法以boolean任何其他方式访问这些值.从技术上讲,vector<bool>甚至不是容器:由于元素的存在chars,迭代器不能被解除引用.

存储位的更好,更清晰的方法是使用bitset该类.

  • 虽然很有见地,但我没有看到这个答案是如何解决这个问题的. (3认同)