c++ - 如何获得支持负索引的 std::vector ?

标签 c++ vector indexing stl c++-standard-library

我有一个 vector 。我想要做的是将值存储在 vector 的第一个索引处。但是,该值用于错误,因此我想引用该值,例如 vector_ [-1] 。我该如何处理这个问题?

我想出了一个解决方案。 我正在做的是创建一个新 vector 并将新 vector 分配给该 vector 。

vector_.resize(required_size+1);
vector_ = std::vector<T> (vector_.begin()+1,vector_.end());

此时我可以合法使用 vector_[-1] ?如果没有,请帮我提供其他解决方案。

编辑 我找到了一个解决方法。虽然它不是具有负索引的 vector ,但我使用的是指向 vector 第二个成员的指针,因此当我执行 ptr[-1] 时,它指向 vector 的第一个元素。

最佳答案

这是 vector 的基本起点,您可以在其中指定(有符号)下索引和上索引

#include <vector>
#include <cassert>
#include <iostream>
#include <iomanip>


template<class T>
struct any_index_vector
{
    any_index_vector(int min, int max)
    : _zero_index(min)
    , _storage((max - min))
    {
        // assert min - max
    }

    T& operator[](int index)
    {
        assert(index >= lower_limit());
        assert(index <= upper_limit());
        return _storage[index - _zero_index];
    }

    T& operator[](int index) const
    {
        assert(index >= lower_limit());
        assert(index <= upper_limit());
        return _storage[index - _zero_index];
    }

    int upper_limit() const {
        return _zero_index + int(_storage.size());
    }

    int lower_limit() const {
        return _zero_index;
    }

    int extent() const {
        return upper_limit() - lower_limit();
    }

    int _zero_index = 0;
    std::vector<T> _storage {};
};

int main()
{
    any_index_vector<int> v(-1, 9);
    for (int i = -1 ; i < 10 ; ++i) {
        v[i] = (i+6);
    }

    for (int i = -1 ; i < 10 ; ++i) {
        std::cout << "position: " << std::setw(2) << i << " : " << v[i] << std::endl;
    }
}

预期输出:

position: -1 : 5
position:  0 : 6
position:  1 : 7
position:  2 : 8
position:  3 : 9
position:  4 : 10
position:  5 : 11
position:  6 : 12
position:  7 : 13
position:  8 : 14
position:  9 : 15

关于c++ - 如何获得支持负索引的 std::vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38382303/

相关文章:

C++ 内存泄漏与 STL vector

c++ - 制作包含结构的 vector 的拷贝

python - 使用特定索引从嵌套列表中提取值

C++ 是否在恒定时间内执行 std::set、std::map 等的 begin/end/rbegin/rend?

使用 CodeSynthesis XSD 树映射的 C++ 类型

c++ - Qt5 中如何判断 QHostAddress 是 IPv4 还是 IPv6?

postgresql - Postgres不会根据where子句中id的具体值来使用索引

c++ - 如何修改 vector 成员的值?

Java Vector `removeElementAt` 函数实际上是如何工作的?

sql - 用数值替换 SQL 索引文本列会使其更快吗?