Vectors and Memory Flashcards
What is the purpose of std::vector in C++?
To provide a dynamic array that allows for random access and automatic expansion of elements
Unlike C-style arrays which have a fixed size, std::vector can grow as needed.
What are the four components of the C++ Standard Library?
- Algorithms
- Containers
- Iterators
- Functions
What is a container in the context of the Standard Library?
A data abstraction that stores a sequence of elements and iterators.
How does a C-style array store elements in memory?
Elements are stored contiguously in memory, allowing random access in O(1) time.
What is one limitation of C-style arrays?
Fixed size; they do not allow for dynamic expansion at runtime.
What is an example of a real-world application that requires dynamic storage?
- Database query responses
- Bluetooth scanning applications
- Chat applications
How can vectors be initialized in C++?
- std::vector<int> v;</int>
- std::vector<int> v(50);</int>
- std::vector<int> v{1,2,3};</int>
What method is used to add an element to the end of a vector?
push_back()
What does the size() method of a vector return?
The number of elements in the vector.
Fill in the blank: The stack memory is organized in a ______ fashion.
LIFO
What type of memory is used for dynamic memory allocation in C++?
Heap memory
What happens if a vector’s capacity is exceeded?
Reallocation to a new memory space is needed.
What does the capacity() function of a vector return?
The total amount of allocated memory for the vector.
True or False: The size of a vector is always equal to its capacity after adding an element.
False
What does the pop_back() method do in a vector?
Deletes the last element of the vector.
What is the maximum number of elements a vector can hold determined by?
Its capacity.
What does the term ‘automatic expansion’ refer to in the context of std::vector?
The ability of a vector to increase its size dynamically as more elements are added.
What is stored in the Code (or Text) segment of memory?
Where the compiled program sits in memory, read-only.
What does the sizeof operator do in C++?
Gives the direct size in bytes of a data type or variable.
What is the typical size of an int data type on a 64-bit CPU?
4 Bytes
What is the role of iterators in the Standard Template Library?
Allow programs to traverse data structures or ranges of elements.
What happens when a vector is initialized with a specified size and default value?
The vector contains that many elements, all initialized to the specified value.
What is a potential consequence of not properly deallocating memory from the heap?
Memory leak errors.
What is the initial capacity of a vector when it is created without any elements?
0