c++ - vector <bool> 迭代器不可解引用

标签 c++ vector

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

enter image description here

这是我的代码:

#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 .因为没有bits C++ 中的单元:他们被迫使用 chars .但是一个字符是 8 位!! C++大神们想出了一个绝招:他们做了一个特殊的成员类型:reference访问 bool 值。您无法访问 boolean任何其他方式的值(value)观。从技术上讲,vector<bool>甚至不是容器:因为元素是 chars ,迭代器不能被取消引用。

一种更好更简洁的存储位的方法是使用 bitset类。

关于c++ - vector <bool> 迭代器不可解引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19696457/

相关文章:

c++ - OSX Yosemite 10.10.3 上的 Cmake - GLEW : package 'gl' not found

c++ - 使用 C++ 映射来计算词频。我究竟做错了什么?

c++ - 将所有 CUDA 函数更改为 __host__ __device__

c++ - 在 C++ 中将子 vector 作为函数参数传递

r - 按位置从 data.table 中提取列作为向量

c++ - 如何处理可能指向内部数据的引用参数?

C++ 读取 WAV 文件的数据部分

c++ - std::vector 与 std::initializer_list 问题:未定义的行为

c++ - 为什么存储此 vector 会出现段错误?

c++ - 用 t 个随机数生成位 vector