Clear vector data in structure | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Clear vector data in structure

As we generally clear vector after usage to have better performance..... Issue I am facing is how to do so when it is structure member? To elaborate, I have one structure having two int and two bool along with one vector... In default constructor, using initialisation of data except vector... Now when class object is used as reference argument of function, data getting filled up in object including vector details also... Should I need to clear vector or is it not necessary? Please feel free to ask for clarification if question is not clear..

19th Nov 2020, 9:24 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
8 Answers
+ 1
To clear the vector you can call myStruct.myVector.clear() If you don't need the data anymore you can clear it but that does not necessarily give any performance boost. If the vector contains system resources that you don't need, you should definitely clear it.
20th Nov 2020, 9:39 AM
The Man
The Man - avatar
+ 1
It should not affect any performance and don't see any reason to clear is explicitly. It would be cleared once the class object goes out of scope.
20th Dec 2020, 2:52 PM
Vipin Chauhan
Vipin Chauhan - avatar
+ 1
Yes the vector will be cleared and you don't have to do anything most of the time. Can think of some scenarios with vector of pointers where pointers where initialized using new operator, there we need to release the memory, as vector clear will not do it.
20th Dec 2020, 5:14 PM
Vipin Chauhan
Vipin Chauhan - avatar
0
So is it like clearing vector doesn't improve performance ? It's main purpose is something I am more interested to know ? Or is it like a good practice only ? Do we loose something by not clearning vector ??
20th Nov 2020, 5:11 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
So what purpose does it serve? Well a scenario might be you want to reuse a filled vector/container to fill fresh set of data. There could be others scenarios too.
20th Dec 2020, 4:25 PM
Vipin Chauhan
Vipin Chauhan - avatar
0
No I don't want to reuse vector as each object has vector for different data.... Confusion of clearing vector come to mind that do we need to clear or not ? Does really object scope and hence compiler provided destructor clears vector or not
20th Dec 2020, 5:06 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
So for most of the general use they are safe to be left alone.
20th Dec 2020, 5:15 PM
Vipin Chauhan
Vipin Chauhan - avatar
0
So in this case , why people suggest to clear vector at the usage end (this is case when it's not part of object and mere vector in function scope)...? Here also doesn't it cleared automatically ? Why we need to clear it manually ? Does this mean that vector used as a part of member variable is cleared by destructor provided by compilers automatically?
20th Dec 2020, 5:18 PM
Ketan Lalcheta
Ketan Lalcheta - avatar