如何通过读取文件来填充矢量?

Ram*_*ngh 0 c++ string vector ifstream

我正在尝试读取一个包含邻接列表的文件

1 37 79 164 15
2 123 134 10 141 13

其中每一行的第一个数字是顶点,后面的数字是它的相邻顶点。

这是我从文件中读取的代码。我已经能够在字符串中放置一行,但不知道如何继续填充向量。

    ifstream ifs;
string line;
ifs.open("kargerMinCut.txt");
std::vector<vector <int> > CadjList(vertices);
while(getline(ifs,line)){
}
Run Code Online (Sandbox Code Playgroud)

有什么建议 ?

Hiu*_*ura 5

Use the power of STL! ;-)

Which gives something like:

// vertex -> adjacent vertices
std::map<int, std::vector<int>> map;

std::string line;
while (std::getline(ifs, line))
{
    std::istringstream is(line);
    std::vector<int> ns;
    std::copy(std::istream_iterator<int>(is), std::istream_iterator<int>(), 
              std::back_inserter(ns));

    assert(ns.size() > 1); // or throw something

    // The first is the vertex
    map[ns[0]] = std::vector<int>(ns.begin() + 1, ns.end());
}
Run Code Online (Sandbox Code Playgroud)

Live example

Alternative implementation, assuming the file is not corrupt:

// vertex -> adjacent vertices
std::map<int, std::vector<int>> map;

std::string line;
while (std::getline(ifs, line))
{
    std::istringstream is(line);
    std::vector<int> ns;

    // assuming we know for sure the file is valid
    auto it = std::istream_iterator<int>(is);
    auto end = std::istream_iterator<int>();
    auto vertex = *(it++); // and not ++it !
    map[vertex] = std::vector<int>(it, end);
}
Run Code Online (Sandbox Code Playgroud)

live example

Generally speaking, <algorithm> contains many nice functions.