Best way to loop from the back on C/C++

Asked 2 years ago, Updated 2 years ago, 30 views

We're going to approach the arrangement from the back to the front I'd like to know a better way than the source code I made

for (int i = myArray.Length - 1; i >= 0; i--)
{
    //take care of sth
    myArray[i] = 0;
}

c c++

2022-09-22 22:30

1 Answers

In general,

for (int i = myArray.Length; i --> 0; )
{
    //do something
}

We use it together.

If you divide it into details, C++ requires different approaches to the array and std::vector.

for(std::vector<T>::reverse_iterator it = v.rbegin(); it != v.rend(); ++it) {
    /* /* std::cout << *it; ... */
}

Note that the index type is not size_t. someVector.size() returns the value of size_type type, not size_t

for(std::vector<int>::size_type i = someVector.size() - 1; i != (std::vector<int>::size_type) -1; i--) {
    /* /* std::cout << someVector[i]; ... */
}
for(std::reverse_iterator<element_type*> it(a + sizeof a / sizeof *a), itb(a); it != itb; ++it) {
    /* /* std::cout << *it; .... */
}

Because sizeof always returns the value of std::size_t type, You can write std::size_t here.

for(std::size_t i = (sizeof a / sizeof *a) - 1; i != (std::size_t) -1; i--) {
   /* /* std::cout << a[i]; ... */
}

But the above method is not an array, but a pointer, so you have to use it carefully.


2022-09-22 22:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.