Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a vector in reverse direction with size_t values

Tags:

c++

vector

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];
    }
}

I will go out of the range of the vector because the r will become 4294967295 after decrementing r = 0.

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.

like image 945
mmostajab Avatar asked Dec 25 '22 01:12

mmostajab


1 Answers

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];
    }
}

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.

like image 181
Codor Avatar answered Feb 22 '23 22:02

Codor