[英]C++ Printing Contents of array backwards One incorrect digit
As part of a program I'm trying to print the contents of an array in reverse order. 作为程序的一部分,我试图以相反的顺序打印数组的内容。 It is working fine except for one value and I can't figure out why. 除了一个值,它工作正常,我不知道为什么。
I haven't gotten onto functions yet so I haven't used them in my code here is the snippet 我还没有接触到函数,所以我没有在代码中使用它们,这里是代码段
case 7:
for (int i = 11; i != -1; i--)// The variable i is initialised to 11. While i is not equal to -1 decrement i by 1.
{
infile >> list[i];//Read in values for array from data.dat
cout << list[i] << " ";// Outputting the array in reverse order.
outfile << "The array in reverse order is: " << list[i] << " " << endl;// Outputting the array in reverse order to file.
}
cout << endl;
break;
The array is filled with the following numbers 数组由以下数字填充
8 16 12 6 16 4 8 10 2 16 12 6 8 16 12 6 16 4 8 10 2 16 12 6
The expected output is: 预期的输出是:
6 12 16 2 10 8 4 16 6 12 16 8 6 12 16 2 10 8 4 16 6 12 16 8
The output I'm getting is: 我得到的输出是:
6 12 16 2 10 8 4 16 6 12 6 8 6 12 16 2 10 8 4 16 6 12 6 8
Any help appreciated 任何帮助表示赞赏
The right way to reverse an iterator is to shift it down by one. 反转迭代器的正确方法是将迭代器向下移动一个。
Forward: 向前:
T a[N];
for (std::size_t i = 0; i != N; ++i)
{
consume(a[i]);
}
Backward: 向后:
T a[N];
for (std::size_t i = 0; i != N; ++i)
{
std::size_t const ri = N - i - 1;
// ^^^
consume(a[ri]);
}
You can write a loop where you actually decrement the loop variable directly, but it's awkward since you either have to use signed integers or otherwise do an additional - 1
when using the index, and it's altogether unnatural, hard to read and easy to get wrong. 您可以编写一个实际上直接递减循环变量的循环,但是这样做很尴尬,因为您必须使用带符号的整数或以其他方式额外使用- 1
在使用索引时为- 1
,而且这完全不自然,难以阅读且容易出错。 I'd much rather recommend always using the forward-moving loop as shown here and compute the reverse iterator separately. 我宁愿建议始终使用此处所示的前向循环并分别计算反向迭代器。
Incidentally, this logic is already encapsulated in the iterator wrapper std::reverse_iterator
, which is build from a normal, bidirectional moving iterator but decrements by one when being dereferenced. 顺便说一句,此逻辑已经封装在迭代器包装器std::reverse_iterator
,该包装器是从正常的双向移动迭代器构建的,但在取消引用时递减1。 You can either reverse a sequence yourself by using make_reverse_iterator
, or by using the free rbegin
/ rend
functions: 您可以使用make_reverse_iterator
自己反转序列,也可以使用免费的rbegin
/ rend
函数反转序列:
#include <iterator>
T a[N];
for (auto rit = std::crbegin(a); rit != std::crend(a); ++rit)
{
consume(*rit);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.