我希望能够索引一个 std::vector,这样当我通过运算符 [] 访问数据时,索引零是下限, vector 的末尾是上限。
这就是我想要做的。不确定如何在 C++ 中执行此操作。
using namespace std;
class Provider
{
public: string name;
};
template <class T>
class Vec : public std::vector<T>
{
private Vec(){}
public Vec(int upperbound, int lowerbound)
{
ub = upperbound;
lb = lowerbound;
}
public:
T& operator[] (int);
private:
int ub;
int lb;
};
//How to do this?
T& VecDQ::operator[] (int idx)
{
return (ub - lb) + idx;
}
int main()
{
int upperBound = 175642;
int lowerBound = 175000;
// I want a Vec of deques<Provider> index such that idx [0] is starting at lowerbound
Vec<std::deque<Provider>> vecOfDeq(upperBound, lowerBound);
//Here, fill the Vec<std::deque<Provider>> with some random examples
// Here, print out Vec[175000].at(1).name << std::endl; // Vec[175000] is really Vec[0]
return 0;
}
最佳答案
您的示例代码中有一些拼写错误
//How to do this?
T& VecDQ::operator[] (int idx)
{
return (ub - lb) + idx;
}
在这里,您告诉编译器您正在定义 VecDQ
类的 operator[]
成员函数。您尚未声明 VecDQ
类,我假设您指的是 Vec
类。除此之外,定义应该在类内部,因为你有一个模板化类,编译器不会知道模板化类之外的“T”是什么。
这是一个可能的定义:
T& operator[] (int idx)
{
return this->at(idx - lb);
}
vector 类的 at
成员函数返回对该索引处项目的引用。您需要从给定的索引中减去下限。
您需要决定是动态调整基本 vector 的大小(当给出新索引时)还是在构造 Vec 派生类时进行。
这是经过上述更改的程序,其中包含一个 Vec 构造函数,该构造函数使用默认构造的元素预先分配基本 vector 。我还为 Provider 类提供了一个构造函数,以便能够使用文字字符串或 std::string 构造它。
关于c++ - 继承自 std::vector<T> 并重载 operator[] 以进行自定义索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26743232/