vector

closed account (jGAShbRD)
if i have a vector a of size 10 holding 10 elements and another vector b of size 20 holding 10 elements if i swap a and b will a have size 20 holding 10 elements and b have size 10 holding 10 elements?
If a vector has size 20 then it's holding 20 elements, not 10. Do you mean that it has capacity 20?

If you swap the vectors with std::swap() the internal pointers will get swapped, so the capacities are swapped as well.
1
2
3
4
5
6
7
8
9
10
11
12
std::vector<int> a, b;
a.reserve(10);
b.reserve(20);
a.resize(10, 0);
b.resize(10, 0);
auto ca = a.capacity();
auto sa = a.size();
auto cb = b.capacity();
auto sb = b.size();
std::swap(a, b);
assert(a.capacity() == cb && a.size() == sb);
assert(b.capacity() == ca && b.size() == sa);
for anything you swap, the a becomes b, and b becomes a, FULLY, not partially ***.
while the compiler may do something smarter, thing of swap as this series of events:

type tmp = a; //full, complete copy of a is created in tmp variable.
a = b; //a is fully assigned all of b
b = tmp; // b is fully assigned all of the copy of a.

*** it is possible to write your own class with a borked up assignment operator that would do a partial copy and you could exploit that to do some extremely convoluted special purpose logic that is really bad code. But for built in types like vector, that will not be the case, you would have to make a 'broken' (bug/mistake) or 'convoluted' class by intent to see this behavior.
Topic archived. No new replies allowed.