SCFAWKS
SCFAWKS

Reputation: 17

Ammending a struct

I have a struct that is filled with vectors.

struct structtype{

vector<double> vec1;
vector<double> vec2;
vector<int> vec3;

};

I want to be able to take the specific elements from one struct and add them to another. Sort of like

structtype myStructA

myStructA.add(myStructB.at(i))

so I'm building myStructA out of specific elements of myStructB. I'm wondering if within the definition of structtype I can just include something like..

struct structtype{

vector<double> vec1;
vector<double> vec2;
vector<int> vec3;

void Add(structtype myStructtoAdd, int i){
vec1.push_back(myStructtoAdd.vec1.at(i));
vec2.push_back(myStructtoAdd.vec2.at(i));
vec3.push_back(myStructtoAdd.vec3.at(i));
};


};

Will this work? And regardless is there a better way to do this?

Upvotes: 0

Views: 74

Answers (2)

alexeykuzmin0
alexeykuzmin0

Reputation: 6440

Yes, this will work.

About the refinement of this code:

Since you need adding element i from one structure to another, probably you may need any other operations over such element, so it looks sensible to define a struct for it, and a retrieving operator:

struct element
{
    double f1, f2;
    int f3;
}

element& structtype::operator [] (int i)
{
    return {vec1[i], vec2[i], vec3[i]};
}

const element& structtype::operator [] (int i) const
{
    return {vec1[i], vec2[i], vec3[i]};
}

After implementation of these operation you probably may store element somewhere else, not only in the structtype, which means that push_back operation with element argument would be useful:

void push_back(const element& e)
{
    vec1.push_back(e.f1);
    vec2.push_back(e.f2);
    vec3.push_back(e.f3);
}

Also, given that the structtype class behaves like a container, it may be useful to implement some other features typical STL containers provide, like iterators. A good guide for STL-like containers implementation is here.

Or, as a second option, you may just use std::vector<element>, which already implements all of these features.

If its functionality is not enough for you, you may extend it creating a new class which inherites the implementation of std::vector. A standard way of doing it is using a private inheritance, like this:

class structtype : private std::vector<element>
{
public:
    /// Write such lines for all members of std::vector which you would like to have
    using std::vector<element>::size(); 
    ...
    /// Write some your own methods
    std::vector<double> get_vec1() const;
}

Upvotes: 0

Giezr
Giezr

Reputation: 19

Yes. It will work, because in c++ struct is very simmilar to class, and they support methods. The difference lies in accessibility of members by default - in class they're private, and in struct they're public. It also applies to inheritance - struct inherits publicly and class - privately (by default - it's still posiblle in both cases to add a desired access specifier)

Upvotes: 1

Related Questions