Question

Assuming a situation where I have:

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

and assuming I need to limit the access to the vector elements for editing and/or reading. What type of indexing (int, long, std::size_t, custom iterator or others) should I use to specify an element in the vector from outside the A class?

Is the following indexing correct?

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

What other options do I have?

Was it helpful?

Solution

You could also use size_type for the index - the same type as your vector:

// 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);

Returning a copy is a good idea - in fact, it's the best thing to do if you want to hide the vector from your callers. Returning a pointer or a reference may be more performant, but it opens up your class to backdoor manipulations, in cases when X is mutable. It also creates an issue if the vector is modified after a reference has been returned, because changing the vector invalidates references to its elements.

You can provide individual functions for manipulating attributes of X, but you could also provide a setter that lets users replace an element of your vector.

OTHER TIPS

Use whatever best fits the design of your class. The fact that your class uses std::vector internally is irrelevant; class interfaces should not be driven by implementation details. Any adjustments, whether of values or types, can be done inside your class. So use std::size_t, unsigned, or whatever.

size_type is a static member type of the type std::vector<X>

And it is a typedef for std::size_t, which itself is usually a typedef for unsigned int or unsigned long long

So can use std::vector<X>::size_type or just std::size_t for indexing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top