使用 size_t 值反向遍历向量 [英] Traversing a vector in reverse direction with size_t values
问题描述
我想以相反的方向遍历向量的值.如您所知,向量的大小为 size_t.当我使用以下代码时:
I want to traverse through the values of a vector in opposite direction. As you know the size of a vector is of size_t. When I use the following code:
for(size_t r=m.size()-1; r >= 0; r--)
{
x[r] = f[r];
for(size_t c = r+1; c < m.size(); c++)
{
x[r] -= m[r][c] * x[c];
}
}
我会超出向量的范围,因为r = 0递减后r会变成4294967295.
I will go out of the range of the vector because the r will become 4294967295 after decrementing r = 0.
我没有改变 r 的类型,因为在我的项目中,我将警告视为错误,所以它应该是 size_t 或者我应该转换它,这并不有趣.
I am not changing the r's type because in my project, I am treating warnings as errors, so it should be size_t or I should cast it which is not interesting.
推荐答案
如果您确实想使用 size_t
进行索引,则可以按如下方式制定循环.
If you actually want to use size_t
for indexing, the loop could be formulated as follows.
for(size_t r = m.size(); r > 0; r--)
{
x[r-1] = f[r-1];
for(size_t c = r; c < m.size(); c++)
{
x[r-1] -= m[r-1][c] * x[c];
}
}
基本上你会从 m.size()
迭代到 1
并通过在循环内移动来补偿;但是这个解决方案可能有点难以遵循.在这个问题中,建议的解决方案是使用reverse_iterator
,可以看作是索引的一个合适的抽象.这个问题更深入地介绍了整个主题.
Basically you would iterate from m.size()
to 1
and compensate by shifting inside the loop; but this solution might be a bit hard to follow. In this question, a proposed solution is to use a reverse_iterator
, which can be seen as a suitable abstraction of the index. The entire topic is coverd in more depth in this question.
这篇关于使用 size_t 值反向遍历向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!