Jaguardo
Jaguardo

Reputation: 333

How to create a C++ user-defined class so that a std::vector of that class does not include certain members of the class

I've created a class that I would like to use in a std::vector of considerable size. However, within that class are members that won't change for each element in the vector (cartesian in the example below). Is there a way to create my class so when I make a vector of it, all the elements in the vector reference to the same variable? Or, more importantly, a way to not use memory for a member that will be the same throughout the entire vector? I don't want to use static because it will remain so for all instances of the class, and this value may change for each vector.

for example

 class foo
 {
 public:
    int x,y,z;
    bool cartesian;
    foo(int _x =0, int _y=0, int _z=0, int _cart = true)
            :x(_x), y(_y), z(_z), cartesian(_cart)
    {
        /* code */
    }
 };


int main(){
    std::vector<foo> vec1;
    vec1.emplace_back(0,0,1);
    vec1.emplace_back(0,0,2);
    vec1[0].cartesian = false;
    cout<< vec1[1].cartesian << endl;
    return 0;
}

I'd like to set cartesian once and have it change for the entire vector (so in this case the 2nd element cartesian member would also become false. Even better I'd like to not use the memory to create it for each element in the vector.

Upvotes: 0

Views: 61

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

No. Just create an associated variable, and pack it together with the vector in a struct.

struct SomeFoos
{
    std::vector<foo> theFoos;
    bool cartesian;
};

Upvotes: 3

Sami Hult
Sami Hult

Reputation: 3082

To answer your question: not really. In c++ instances of a single class are identical in their structure. Even if you have a shared reference to a value you want to share, you will gain no benefit in terms of memory usage, unless the value is an object larger than sizeof(void*).

But since you say "I'd like to set cartesian once and have it change for the entire vector" which I read: "set cartesian attribute for the vector":

I suggest that you create a container class that has vector as superclass; your class will inherit vector's behaviour, and you can add the shared values in instances of that container class.

Upvotes: 1

Related Questions