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)
有什么建议 ?
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 and std::ostream_iterator to read and write to stream with an iterator interface, very useful in combination with std::copy.std::back_inserter to use push_back with std::copy.std::vector's constructor can take iterators to initilize its content.std::map might be better than a std::vector if your vertex are not a continuous range starting from 0.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)
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)
Generally speaking, <algorithm> contains many nice functions.
| 归档时间: |
|
| 查看次数: |
4676 次 |
| 最近记录: |