Nikita
Nikita

Reputation: 67

Access to several containers in the class

Suppose there is a class with several (e.g. 2) containers as private members. Would that be good to have different kinds of begin() (or at()) member functions to access iterator (or element) of the corresponding container?

Here is the small example:

class Example
{
private:
    std::vector<double> A;
    std::vector<double> B;
public:
    double& A(std::size_t index) { return A.at(index); }
    double& B(std::size_t index) { return B.at(index); }
};

I need to have such kind of access because there is one class that asks for the values in container A and there is also another class asking for the contents of B. In general class Example might have more than two containers.

Is that a good idea or there is better solution?

Thanks

EDIT

Here is some additional information: container A Holds always some parameters that will be passed to different functions, container B holds the values return from the function that has been passed container A as an argument. And the rest of possible containers will hold different constraints on the values that can be stored in A

Upvotes: 0

Views: 71

Answers (3)

Neil Kirk
Neil Kirk

Reputation: 21813

Does anything outside of the class care about the contents of these vectors? If not, create a member function to take a function pointer and use it with the vectors. Then you don't need to expose the vectors. Fully exposing internal objects with get functions defeats the point of making them private.

Upvotes: 1

4pie0
4pie0

Reputation: 29764

It sounds like you need such accessors. You might consider putting const keyword on the returned value if elements doesn't have to be modified

const double& getA(std::size_t index) { return A.at(index); }

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110778

If there might be more, it seems like you actually have some kind of "list" of containers. Almost like your naming scheme A, B, ... is just enumerating them, which is always a sign you should be using some sort of container. Then maybe you actually want a container of std::vectors? If it's a fixed amount, something like:

std::array<std::vector<double>, N> containers;

If it's not fixed, then:

std::vector<std::vector<double>> containers;

Then you could have a single function that asks for the index of the container and then an index within that container:

double& get(std::size_t container, std::size_t element) {
  return containers[container][element];
}

Upvotes: 0

Related Questions