这是一个解决方案:
struct Edge
{
int x;
int y;
friend std::istream& operator>>(std::istream& input, Edge& e);
};
std::istream& operator>>(std::istream& input, Edge& e)
{
input >> e.x;
input >> e.y;
return input;
}
这是一些主要代码:
int node_quantity = 0;
std::vector<Edge> database;
std::cin >> node_quantity;
// Ignore the newline following the number.
std::cin.ignore(1000, '\n');
// Start at the beginning of the line.
std::string text_line;
std::getline(std::cin, text_line);
// Read in the edges
std::istringstream text_stream(text_line);
Edge e;
while (text_stream >> e)
{
database.push_back(e);
}
operator>>
上面的代码创建了一个边缘结构和用于读取边缘的 重载。
第二个代码片段读入一行边缘并使用 astd::istringstream
读取文本行中的所有边缘。