简体   繁体   中英

Access array in reverse order c++

I have the following piece of code

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

How can I access its elements in reverse order, without reversing the indices. I mean index 0 would return the last element (20), and index 2 would return the first element (10).

array[0] // it would return 20

Thanks in advance

It is a simple math question. array[n] from the back is simply array[array_size - 1 - n] from beginning.

Personally I will make up a little wrapper for the array if similar logic needs to be used in more than 1 place.

Psuedo code looks like:

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;
}

so that you can do

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

int result = quote_in_reverse[0]; // result = 20

This may help you

#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;
}

Another thing is that computer starts counting from 0. So you should give four values to your quote int quote[3]={10, 20, 30, 40} quote[0] is 10 and quote [3] is 40.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM