Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is vector in struct time consuming? Is it better to use a pointer?

I have a struct in C++ like this:

struct MyStruct 
{
    someType v1;
    someType2 v2;    
    someType3 v3;
    someType4 f1();

    std::vector<someType> myVector;
} ;

It will be very often used in forms like this:

 //some process... after which a std::vector<someType> vec1 is generated 
 MyStruct myStruct;    
 myStruct.myVector = vec1;

Since vec1 is relative large. I want to know if it costs much time by doing the assignment myStruct.myVector = vec1;

Should I use a pointer to myVector in MyStruct to make it faster? And how?

like image 570
Summer Fang Avatar asked Oct 17 '17 11:10

Summer Fang


2 Answers

Since vec1 is relative large. I want to know if it costs much time by doing the assignment

It costs time in linear proportion to the size of the vector.

Should I use a pointer to vec in MyStruct to make it faster?

Given the problem that you've described, no I would not suggest you use a pointer unless you've left out relevant details.

You could move assign the vector (since C++11), or swap it (prior to C++11). But that assumes that you don't need vec1 for anything else.

like image 192
eerorika Avatar answered Nov 15 '22 02:11

eerorika


There is a fundamental difference between std::vector<someType> myVector and std::vector<someType*> myVector. The non-pointer version actually owns and stores the data. This means once the assignment is made changes to the original variable will not result in changes to your vector (deep copy).

In the pointer version, storage is external to the vector. This means that changes to the original will result in changes to your vector (shallow copy). The is another knock on effect as well.

Since storage is external to your vector, it is your responsibility to ensure that the original sticks around for longer than your vector. Otherwise bad things will happen. This can be mitigated with a std::shared_ptr but you are still aliasing the same memory.

So the question you need to ask is whether you require a shallow copy or a deep copy.

Also std::move will only save you a copy if data is stored external to the struct (like an stl-container) otherwise you will need to move a std::unique_ptr<someType> to save the copy.

like image 44
doron Avatar answered Nov 15 '22 03:11

doron