user14578333
user14578333

Reputation:

Will Calling clear() on a vector of lists clear all the nodes in the list at each index?

I am creating a hash table that has a private data member vector<list<pair<K, V>>> hashTable;. My understanding is that a rehash function should assign the elements of the original table to a temp table, empty the original table, resize it, the hash the elements of the temp table back into the original table.

Will an assignment such as vector<list<pair<K,V>>> tempTable = origTable; make a deep copy? Or do I need to declare tempTable to be the same size as original table and then go through each list at each index and add it to tempTable?

Finally, will calling origTable.clear(); empty out all the nodes in each list at each index and reclaim the memory correctly or do I need to step through each index and explicitly empty each list?

Thanks

Upvotes: 1

Views: 74

Answers (3)

eerorika
eerorika

Reputation: 238361

Yes. Copy assignment of vector is deep. The elements will be copied.

Calling clear will erase all elements from the standard vector. All of those objects are destroyed. The destructor of the standard iterator destroys all of its nodes.

Upvotes: 0

Chris Uzdavinis
Chris Uzdavinis

Reputation: 6131

vector<list<pair<K,V>>> tempTable = origTable;

Everything will copy, from the vector, list, and pair all the way through to K and V. However, it's worth considering that if K and/or V are themselves pointers, then the pointer will be copied but the object they point to will not, and you will have aliasing.

Upvotes: 1

orlp
orlp

Reputation: 117701

The convention for types in C++ is to have copy semantics, and std::vector, std::list and std::pair all adhere to this.

Therefore vector<list<pair<K,V>>> tempTable = origTable; does a 'deep copy', and no reference to the old data is kept. And similarly calling .clear() on such a vector will destroy all used memory.

Upvotes: 2

Related Questions