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.
© 2024 OneMinuteCode. All rights reserved.