Reading and inserting into vector when overloading []

时间:2017-03-28 16:36:02

标签: c++ vector operator-overloading

I'm trying to make a class that ovreloads an operator []. my Code looks like this:

class DynamicArray{
public: 
DynamicArray(){
}
 double operator[](unsigned int i) const{
 return values.at(i);
}
double &operator[](unsigned int i){
values.insert(values.begin()+i, ??? );
}
private:
vector<double> values;
}

i want to call it like this(array is object of DynamicArray):

cout << array[5];

this works fine but i also want to do something this:

array[5] = 5.4;

but I'm clueless how i could do this. (i know i could use just vector but i need to do loads of stuff in the class). My question is - How can i change the second overload so it does assign the value to that index in vector ? EDIT: To clarify: I don't know how many values or where it will be put so i need ti to resize accordingly.

1 个答案:

答案 0 :(得分:1)

您的非const operator[]函数应如下所示:

double & operator[](size_t index) {
    if(index >= values.size())
        values.resize(index + 1);
    return values[index];
}

这应该传达你想要的语义。

编辑:我将在评论中使用std::mapstd::unordered_map来代表这种数据结构,因为它允许您编写使用任意索引的代码强制将所有内容存储在连续内存中,这是std::vector的约束。但是我要在这里留下解决方案,因为将所有存储在连续内存中的内容可能是一个设计要求(特别是如果这是用于图形应用程序),所以有些情况下像这样的解决方案具有逻辑意义。