繁体   English   中英

逆序存取阵列 c++

[英]Access array in reverse order c++

我有以下一段代码

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

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

array[0] // it would return 20

提前致谢

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

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

伪代码如下所示:

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] 是 10,报价 [3] 是 40。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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