我正在关注这本好书 C++17 by Example ,它通过展示一系列迷你项目来介绍 C++17——非常酷。
然而,在第 2 章中,Set
是在 LinkedList
之上实现的,有这段代码:
void Set::read(std::istream& inStream) {
int size;
inStream >> size;
int count = 0;
while (count < size) {
double value;
inStream >> value;
insert(value);
++count;
}
}
void Set::write(std::ostream& outStream) {
outStream << "{";
bool firstValue = true;
Iterator iterator = first();
while (iterator.hasNext()) {
outStream << (firstValue ? "" : ", ") << iterator.getValue();
firstValue = false;
iterator.next();
}
outStream << "}";
}
int main() {
Set s, t;
s.read(std::cin);
t.read(std::cin);
std::cout << std::endl << "s = ";
s.write(std::cout);
std::cout << std::endl;
std::cout << std::endl << "t = ";
t.write(std::cout);
std::cout << std::endl << std::endl;
// snip
}
我是 C++ 的新手,我不知道如何运行它。当然,我在问之前做了一些研究,但我想出的方法并没有产生预期的结果:
lambdarookies-MacBook:02-the-set-class lambdarookie$ ./02-the-set-class
1 2 3
3 4 5
s = {2} // Expected: s = {1, 2, 3}
t = {3, 4, 5}
现在我想知道:
- 这是否根本不是提供论据的正确方式,或者
- 这是正确的方法,错误一定在代码的其他地方吗?
最佳答案
Set::read
读取的第一个数字是集合的大小。然后它读取那么多数字,并将它们添加到集合中。该行的其余部分被当前调用的 read
忽略,并被下一个调用拾取,巧合的是,它是您正在测试的下一组的大小。因此,输入 1 2 3
会得到一个大小为 1
的集合,其中只有一个元素 2
。
请注意:hasNext
是一种 java 主义,不同于通常的 C++ 迭代器的工作方式。或许您还可以考虑阅读其他手册。
关于c++ - 此函数期望从 std::istream 解析什么格式的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56315927/