+ 3

Vectors array [Solved]

In the following code the array having 4 elements prints the value of its 5th element and I don't know how? May be it has something to do with Vectors, as I am new in it, I don't know much about it Please help https://code.sololearn.com/cBiF9vHUQm47/?ref=app

28th May 2019, 9:38 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
8 Respuestas
+ 4
Oh, now I see. First you allocate a vector with 5 elements in main. printvec then copies the vector and you give that new vector a new range of numbers, 4 numbers this time. That means that the vector already has a container that CAN contain 5 elements. So why would it need to allocate a new array when it can fit those 4 new elements inside the old array? It simply changes 88,97,95,95,86 into 97,95,95,88, [86]. That 86 is not removed from memory, doing so would waste cpu cycles for no reason. It simply changes the internal state from 5 elements to 4. If you then decide to access the 5th element, that's on you.
29th May 2019, 12:18 PM
Dennis
Dennis - avatar
+ 4
Just like regular arrays, a vector's index starts at 0, so the 4th element is located at n[3]. n[4] ( 5th element ) behaves the same way as it would on regular arrays with 4 elements, undefined behavior. Most things in C++ is all about speed. Range checking and potentially throwing in every function is not the best idea. n.at( 4 ) does do range checks and that does throw an exception into your face if you want to sacrifice speed for safety ( might be a good idea in debugging ). Additionally, a vector is really expensive to copy, so you probably want to take it by (const) reference.
28th May 2019, 10:10 PM
Dennis
Dennis - avatar
+ 3
Dennis but what is the reason behind this I didn't get it
29th May 2019, 4:11 AM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 3
Saurabh Tiwari Reason about what? C++ just doesn't hold your hand.
29th May 2019, 8:07 AM
Dennis
Dennis - avatar
+ 3
Dennis why n[4] exists and why n.at(4) throws an error Is the compiler confused between the two vectors 😅
29th May 2019, 12:09 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 3
Dennis thanks Compiler is smart 😎 What about n.at(4) It throws an error
29th May 2019, 12:23 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 3
Yea, because, like I said, the internal state of the vector changed from 5 to 4 elements and the at function does a range check. at() works something like this: template<typename T, typename Allocator> (const) T& vector<T, Allocator>::at( size_t index ) (const) { if( !(index < m_size) ) throw std::out_of_range( "vector::range_check: __index (which is " + std::to_string( index ) + ") >= this->size() (which is " + std::to_string( m_size ) + ")" ); return m_data[index]; } https://en.cppreference.com/w/cpp/container/vector/at
29th May 2019, 12:27 PM
Dennis
Dennis - avatar
+ 3
Thanks Dennis Gotta learn more to understand that code snippet
29th May 2019, 12:43 PM
Saurabh Tiwari
Saurabh Tiwari - avatar