为什么此代码无法打印队列中的所有值?

时间:2017-01-14 20:19:22

标签: c++

你能解释为什么代码不打印队列中的所有值,q。

for (int i = 0; i < q.size(); ++i)
    std::cout << q.dequeue() << std::endl;

2 个答案:

答案 0 :(得分:2)

每次拨打%s/[:\|?].*/:\|?时,显然q.dequeue()会减少,而您只会输出大约一半的队列元素。因此,您可能希望在开始迭代之前缓存初始大小,例如

q.size()

答案 1 :(得分:2)

与保罗R的答案逻辑相似。队列中的项都是出队的,所以循环直到队列为空。

 MariaDB [l]> drop table int6;
 Query OK, 0 rows affected (0.00 sec)

MariaDB [l]> CREATE TABLE `int6` (
    ->   `id` int(6) unsigned zerofill NOT NULL AUTO_INCREMENT,
    ->   PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.02 sec)

MariaDB [l]> insert into int6 VALUES (1),(2),(3);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

MariaDB [l]> select * from int6;
+--------+
| id     |
+--------+
| 000001 |
| 000002 |
| 000003 |
+--------+
3 rows in set (0.00 sec)

MariaDB [l]>