I am trying to read a file which contains the adjacency list as
1 37 79 164 15
2 123 134 10 141 13
where first number in every line is vertex and following numbers are its adjacent vertices.
This is my code to read from the file . I have been able to put a line in a string but don't know how to proceed to populate the vector.
ifstream ifs;
string line;
ifs.open("kargerMinCut.txt");
std::vector<vector <int> > CadjList(vertices);
while(getline(ifs,line)){
}
Any suggestions ?
You can use
stringstream
in the sstream header.Code in the while loop:
Use the power of STL! ;-)
std::istringstream
to create a stream from a string.std::copy
to copy stuff from something to something else (yes, it can be that generic!).std::istream_iterator
andstd::ostream_iterator
to read and write to stream with an iterator interface, very useful in combination withstd::copy
.std::back_inserter
to usepush_back
withstd::copy
.std::vector
's constructor can take iterators to initilize its content.std::map
might be better than astd::vector
if your vertex are not a continuous range starting from 0.Which gives something like:
Live example
Alternative implementation, assuming the file is not corrupt:
live example
Generally speaking,
<algorithm>
contains many nice functions.