我有一个 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/