我希望能够对std :: 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;
}
在这里,您告诉编译器您正在定义
operator[]
类的VecDQ
成员函数。您尚未声明VecDQ
类,我假设您的意思是Vec
类。除此之外,定义应该在类内部,因为您有模板类,编译器将不知道模板类之外的“ T”是什么。这是一个可能的定义:
T& operator[] (int idx)
{
return this->at(idx - lb);
}
向量类的
at
成员函数返回对该索引处项目的引用。您需要从给定的索引中减去下限。您将需要决定是动态调整基向量的大小(给定新索引时)还是在构造Vec派生类时进行调整。
这是带有上述更改的程序,带有Vec构造函数,该构造函数使用默认构造的元素预分配基本向量。我还为Provider类提供了一个构造函数,以便能够使用文字字符串或std :: string构造它。
http://coliru.stacked-crooked.com/a/40f5267799bc0f11
关于c++ - 继承自std::vector <T>和重载operator []以进行自定义索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26743232/