是的,C++中的容器和數組都支持逆序遍歷??梢允褂媚嫦虻骰蛘吆唵蔚貜淖詈笠粋€元素開始向前遍歷來實現逆序遍歷。例如,對于一個數組arr,可以使用以下方式來進行逆序遍歷:
int arr[] = {1, 2, 3, 4, 5};
// 使用逆向迭代器進行逆序遍歷
for (auto it = std::rbegin(arr); it != std::rend(arr); ++it) {
std::cout << *it << " ";
}
// 從最后一個元素開始向前遍歷
for (int i = 4; i >= 0; --i) {
std::cout << arr[i] << " ";
}
對于STL容器,也可以使用rbegin()
和rend()
函數獲取逆向迭代器進行逆序遍歷。例如,對于一個vector:
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用逆向迭代器進行逆序遍歷
for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
std::cout << *it << " ";
}