📜  vector :: crend()和vector :: crbegin()的示例(1)

📅  最后修改于: 2023-12-03 15:20:58.628000             🧑  作者: Mango

Intro to vector::crend() and vector::crbegin() in C++

In C++, the vector container provides two member functions crend() and crbegin() to access the reverse range of elements. These functions are useful when you need to iterate over the container in reverse order without modifying its elements.

vector::crend()

The crend() member function returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (i.e., the element before the first element in the reverse iteration). It can be used to check the end of a reverse iteration loop condition.

Here's an example demonstrating the usage of crend():

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    for (auto it = numbers.crbegin(); it != numbers.crend(); ++it) {
        std::cout << *it << " ";
    }
    
    return 0;
}

Output:

5 4 3 2 1

In this example, we iterate over the vector in reverse order using crbegin() and crend(). Each element is accessed using the reverse iterator it and printed to the standard output.

vector::crbegin()

The crbegin() member function returns a constant reverse iterator pointing to the last element in the vector. It allows you to access the elements in reverse order starting from the last element.

Here's an example illustrating the usage of crbegin():

#include <iostream>
#include <vector>

int main() {
    std::vector<char> characters = {'A', 'B', 'C', 'D', 'E'};

    auto rit = characters.crbegin();
    std::cout << *rit << std::endl;  // Output: E

    return 0;
}

In this example, we obtain the constant reverse iterator rit using crbegin() and directly access the last element of the characters vector using *rit.

Conclusion

In summary, the vector::crend() and vector::crbegin() member functions provide easy ways to access the reverse range of elements in a vector. These functions can be particularly useful when you need to iterate over the container in reverse order without modifying its elements.