我正在阅读一本很棒的书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}
现在我在想:
发布于 2019-05-27 01:45:49
Set::read
读取的第一个数字是集合的大小。然后它读取这么多数字,并将它们添加到集合中。该行的其余部分被当前的read
调用忽略,并由下一个调用获得,巧合的是,下一个集合的大小就是您要测试的下一个集合的大小。因此,输入1 2 3
会产生一组大小为1
的元素,其中只有一个元素2
。
请注意:与通常的C++迭代器的工作方式不同,hasNext
是java风格的。也许你也可以考虑看看不同的手册。
https://stackoverflow.com/questions/56315927
复制相似问题