以反向顺序访问数组

Access array in reverse order c++

本文关键字:访问 数组 顺序      更新时间:2023-10-16

我有以下一段代码

int array[3] = { 10, 15, 20};

如何以反向顺序访问其元素,而不反转索引。我的意思是索引0将返回最后一个元素(20),索引2将返回第一个元素(10)。

array[0] // it would return 20

Thanks in advance

这是一道简单的数学题。后面的array[n]就是开头的array[array_size - 1 - n]

如果需要在多个地方使用类似的逻辑,我个人会为数组创建一个小包装器。

Psuedo代码如下:

template <T> class reverse_array {
public:
    reverse_array(T* array, size_t size)
        : m_array(array), m_size(size) {}
    operator T& [] (size_t index) {
        return m_array[m_size - 1 - index];
    }
    operator const T& [] (size_t index) const {
        return m_array[m_size - 1 - index];
    }
private:
    T* m_array;
    size_t m_size;
}

这样你就可以做

int quote[3] = { 10 , 15 ,20};
reverse_array quote_in_reverse(quote, 3);
int result = quote_in_reverse[0]; // result = 20

这可能对你有帮助

#include <iostream>     
#include <algorithm>    
#include <vector>       
using namespace std;
int main () {
  vector<int> a;
  //Function goes here
  for (int i=0; i<=5; ++i){
      a.push_back(i);   //Values are: 0 1 2 3 4 5
  }
   // Reverse process
  (a.begin(), a.end());    // Values are: 5 4 3 2 1 0
  //Print the result
  for (vector<int>::iterator it=a.begin(); it!=a.end(); ++it)
  cout<<"new reverse 'a' is: "<<*it;
  return 0;
}

另一件事是计算机从0开始计数。所以你应该给你的报价int quote[3]={10, 20, 30, 40}四个值引用[0]是10quote[3]是40