簡體   English   中英

矢量<bool>迭代器不可解引用

[英]vector <bool> iterator not dereferencable

我在編寫程序后嘗試調試我的程序,但遇到了這個錯誤:

在此處輸入圖片說明

這是我的代碼:

#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;
}

我為煩人的格式道歉 =/。 它在 dij 方法的最后一個 for 循環中中斷。 有誰知道我可能會遺漏什么?

稻田說得對!

但作為建議,不要使用vector<bool> ...

看,C++ 眾神想要創建一個節省空間的存儲結構來存儲bools 為了提高空間效率,他們使用了bits 因為 C++ 中沒有bits單位:他們被迫使用chars 但是一個字符是 8 位!! C++ 大神想出了一個獨特的解決方案:他們制作了一個特殊的成員類型:訪問 bool 的reference 您不能以任何其他方式訪問boolean值。 從技術上講, vector<bool>甚至不是一個容器:由於元素是chars ,迭代器不能被取消引用。

一種更好、更bitset存儲位的方法是使用bitset類。

我認為您在這些向量中預填充了錯誤數量的元素。 您正在迭代g.indices.size() ,它應該是g.vertices.size()

您的其余代碼知道indices可以比vertices短。 使用從索引中提取的值對checkdistanceprev向量進行indices 您得到的運行時錯誤可能是由於調試模式下的迭代器邊界檢查造成的。

這應該可以解決您的問題:

for (int i = 0; i <= g.vertices.size(); i++)  // <-- notice the change here
{
    check.push_back(false);
    distance.push_back(MAXINT);
    prev.push_back(-1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM