以反向顺序访问数组
Access array in reverse order c++
我有以下一段代码
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
相关文章:
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 使用指针访问数组中的对象数据成员
- VTK 图像数据,访问数组中的 1 个图像
- 调用函数后无法访问数组
- 如何从地图访问数组的元素?
- 访问数组中的不同元素
- 使用指针访问数组元素时出现意外结果
- 使用指针访问数组的值
- C++基于1而不是0的访问数组,方法是在编译时移位
- 如何在主函数之外访问数组?
- 如何在 llvm 的 cpp api 中使用 CreateInBoundsGEP 来访问数组的元素?
- 访问数组中所有结构的成员
- C 是否每次访问数组时都复制元素?
- C++ 为什么访问数组中的元素会返回指针?
- 如何通过指针访问数组的元素
- 指针数组交换无需直接访问数组
- 直接从指针/地址访问数组的元素
- 我有一个 Qt 对象的 2d 数组,我已经用值播种了这些对象。如何访问数组中特定对象的值并更改它们?
- 如何使用 C+ 中的指针访问数组中的特定索引
- 通过两个下标访问数组成员