Is the vector in the structure a long time? Is it better to use a pointer?

I have a structure in C ++, for example:

struct MyStruct { someType v1; someType2 v2; someType3 v3; someType4 f1(); std::vector<someType> myVector; } ; 

It will be very often used in such forms:

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

Since vec1 is relatively large. I want to know if it costs a lot of time doing the assignment myStruct.myVector = vec1;

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

+5
source share
2 answers

Since vec1 is relatively large. I want to know if it costs him a lot of time completing an assignment.

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

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

Given the problem that you described, I would not suggest you use a pointer if you did not provide the relevant data.

You can move the destination of the vector (starting with C ++ 11) or change it (before C ++ 11). But this suggests that you do not need vec1 for anything else.

+11
source

There is a fundamental difference between std::vector<someType> myVector and std::vector<someType*> myVector . A version other than pointers actually owns and stores data. This means that after making the task, changes to the source variable will not lead to a change in your vector (deep copy).

In the version of the pointer, the storage is external to the vector. This means that changes in the original will lead to a change in your vector (small copy). This is another blow to the effect.

Since the repository is external to your vector, you are responsible for making the original fall longer than your vector. Otherwise, bad things will happen. This can be mitigated with std::shared_ptr , but you are still imposing the same memory.

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

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

+2
source

Source: https://habr.com/ru/post/1272696/


All Articles