c++ - 如何提高邻接表分配的速度?

标签 c++ data-structures graph adjacency-list

在确定 adjacency matrix 不适用于 80513 节点和 5899882 边后,我已经决定应用邻接表。这是我第一次实现邻接表,基本上我决定应用 vector 方法的 vector 。

因此,例如,vectorOfVectors[5] 将包含包括邻居节点5。可以找到我正在使用的数据集 here

目前我已经编写了这段代码并且它可以正常运行,但是在我的电脑上它需要 26 秒(i5 2.4 和 6 GB 内存,运行 Win7)。我想知道是否可以改进我的代码以降低分配速度。

PS:我正在使用 fstream 库并从 .csv 文件中读取数据。

#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>

using namespace std;

int main()
{
    ifstream file("edges.csv");
    string word="",data="";
    getline(file,word);
    int arrTemp[3];
    int numberOfNodes=atoi(word.c_str());
    vector<int>temp;
    vector< vector<int> >adjacencyList;

    for(int i=0;i<numberOfNodes;i++)
    {
        adjacencyList.push_back(temp);
    }
    while(file.good() && getline(file,word))
    {
        //cout<<word<<endl;
        if(word.size()>0)
        {
            for(int i=0;i<3;i++)
            {
                int cutFrom=word.find_first_of(',');
                arrTemp[i]=atoi(word.substr(0,cutFrom).c_str());
                word=word.substr(cutFrom+1,word.length());
            }
            //cout<<arrTemp[0]<<" "<<arrTemp[1]<<endl;
            adjacencyList[arrTemp[0]-1].push_back(arrTemp[1]-1);

        }
        else
            break;
    }

    cout<<"Vector size:"<<adjacencyList[1].size()<<endl;
    return 0;
}

最佳答案

更好的方法是节点索引对的unordered_set(其中索引对总是首先列出较小的节点)。

关于c++ - 如何提高邻接表分配的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10097205/

相关文章:

c++ - 使用 Microsoft Access 数据库在 C++ 中进行 Unicode 转换

algorithm - 如果从通用哈希函数族中随机选择哈希函数,如何找到给定键的值?

javascript - 如何为数组中的每个对象添加唯一 ID?

python - 图中带有标记边的最短路径

ruby - 如何在不保存到磁盘的情况下通过电子邮件在 Ruby 中发送图形?

c++ - 为什么 std::getline() 在格式化提取后跳过输入?

c++ - boost ASIO streambuf

java - 为什么我们可以将 null 元素添加到 java LinkedList?

javascript - ECharts:如何使用窗口的resize事件?

c++ - 使用二元谓词函数的模板作为参数(std::greater,std::equal_to)C++