太多我从标准输入下列输入:istream_iterator消耗从流
2
5
2 1 5 3 4
5
2 5 1 3 4
第一行代表队列数(我们称之为价值n
)。然后,对于每个队列,在第一行中有一个值l
,表示队列的长度,后面是实际的队列。
我试图用istream_iterator
如下把队列中的向量:
using namespace std;
int n{};
int l{};
typedef std::istream_iterator<int> input_iterator;
cin >> n;
cout<< "n: " << n << "\n";
for(int i = 0; i < n ; ++i){
cin >> l;
cout << "l: " << l << "\n";
std::vector<int> queue;
int counter = 0;
for (input_iterator it(cin); counter < l && it != input_iterator(); ++it){
queue.push_back((*it));
++counter;
}
cout<< "Queue: ";
std::copy(queue.begin(), queue.end(),
std::ostream_iterator<int>(std::cout, " "));
cout << "\n";
}
此代码产生以下输出:
n: 2
l: 5
Queue: 2 1 5 3 4
l: 2
Queue: 5 1
正如你所看到的第一个队列中读取正确。但第二个l
应该是5
,而不是2
。
发生了什么事5
?它是否被迭代器使用?我在哪里犯了一个错误?
在调试器中逐行执行代码。并停止阴影变量,在内部循环中为迭代器使用另一个名称。另外,是否有你想使用输入迭代器的原因,而不仅仅是一个简单的循环,你可以使用简单的'std :: cin >> ...'来获取值? –
这和整个阴影事实上是写这个例子发生的错误。我修正了这一点 – user2393256