my vector size seems to be strangely big, the revesreVev function takes in a pointer to a vector as it's arguments and sets that pointer equal to a new reversed vector
but when I return from the function and print the vector n's size it prints a huge number , it should print 4 as that is the size of the vector
oh ok so when I pass n to the reverseArray vec, a copy is created called nums?
so now both nums and n are pointing to the same data?
in the function I delete the data that is pointed to by both nums and n, and set numbs only to point to the new vector, but n does not point to this vector?
I have essentially deleted n's data and when the function goes out of scope newNumbs is now also out of scope and I have leaked memory?
The short answer: pass numb by reference: void reverseVec(vector<int>* &numbs){
Right now you're passing the pointer numb by value. So numb (in reverseVec) is a different variable than n (in main). However, they point to the same vector.
Line 20 in the first program deletes numb. Now numb and n point to unallocated memory.
Line 21 assigns numb to the new vector, but when reverseVec returns, that value is lost. n still points to the now-deleted vector and when you print the size at line 35, you get garbage.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> n {6, 7, 8, 9};
std::reverse( n.begin(), n.end() );
for ( int x : n ) {
std::cout << x << '\n';
}
}
that would have been a lot simpler, yeah there isn't much point of a having the vector allocated on anything other than the stack for this simple case. that is much more elegant, I was just doing an exercise in Bjarnes book to reverse the contents of a vector, I was trying to do it as many ways as I could think of
> there isn't much point of a having the vector allocated on anything other
> than the stack for this simple case
¿can you think of any case were there is any point in doing new vector<int>?
then again maybe when returning a vector from a function( which you delete after you're done with it) the reason I say this is because you could obviously return a copy of a vector but that copy is expensive(especially if the vector contains thousands of objects ) and if you return a pointer to a vector it will be less expensive processing wise.
> returning a vector from a function
move assignment
1 2 3 4
class vector{
T *data;
int size, capacity;
};
the containers are lightweight, they just have a couple pointers a = b doing a deep-copy is expensive, but if `b' is going to die inmediately after, you can make it shallow (with some care)
The std::reverse() works in-place; without additional memory.
You had a temporary vector into which you did copy values (like std::reverse_copy() does) and then attempted to swap the vectors. That could be shortened to: