我应该如何从类外部索引私有向量?

时间:2013-08-11 15:06:45

标签: c++ stl containers std size-t

假设我有这样的情况:

class A {
private:
    std::vector<X> _v;
    // ...
public:
    A();
    // ...
};

并假设我需要限制对矢量元素的访问以进行编辑和/或阅读。我应该使用什么类型的索引(intlongstd::size_t,自定义迭代器或其他类型来指定A类外部的向量中的元素?

以下索引是否正确?

class A {
    // ...
    X getVectorElement(std::size_t);
    void editSomeElementValue(std::size_t, double); // double is the type of the value to edit
};

我还有其他选择吗?

3 个答案:

答案 0 :(得分:1)

您还可以使用size_type作为索引 - 与向量相同的类型:

// Make your own type for the index based on the vector's index type
typedef std::vector<X>::size_type size_type;
// Use your typedef in the declaration of your getter
X getVectorElement(size_type index);

返回副本是个好主意 - 事实上,如果你想隐藏来自你的来电者的矢量,这是最好的办法。返回指针或引用可能更高效,但是在X可变的情况下,它会打开您的类以进行后门操作。如果在返回引用后修改了向量,它也会产生一个问题,因为更改向量会使对其元素的引用无效。

您可以提供单独的函数来操作X的属性,但您也可以提供一个setter,让用户替换向量的元素。

答案 1 :(得分:1)

使用最符合你班级设计的东西。你的班级内部使用std::vector的事实无关紧要;类接口不应由实现细节驱动。任何调整,无论是值还是类型,都可以在类中完成。因此,请使用std::size_tunsigned或其他任何内容。

答案 2 :(得分:0)

size_typestd::vector<X>

类型的静态成员类型

它是std::size_t的typedef,它本身通常是unsigned intunsigned long long

的typedef

因此可以使用std::vector<X>::size_typestd::size_t进行索引。