以相反顺序访问数组c ++

时间:2016-08-12 02:59:06

标签: c++ arrays

我有以下代码

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

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

array[0] // it would return 20

提前致谢

2 个答案:

答案 0 :(得分:4)

这是一个简单的数学问题。从后面开始的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

答案 1 :(得分:-2)

这可能对您有所帮助

#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} quote [0]是10 并且引用[3]是40。

相关问题