Choose a container by its access pattern
std::vector stores elements contiguously and supports fast indexed access. std::list is a doubly linked sequence and supports insertion or erasure at a known position without moving all following elements. A vector is a strong default for a simple growing list; a list is not automatically faster just because insertion can be constant time.
Vector example
#include
#include
#include
int main() {
std::vector marks{62, 75};
marks.push_back(83);
marks.at(0) = 65;
for (int mark : marks) std::cout << mark << ' ';
std::cout << "size=" << marks.size() << '\n';
std::list queue{10, 20};
queue.push_front(5);
queue.pop_back();
for (int item : queue) std::cout << item << ' ';
std::cout << '\n';
}
The vector contains 65, 75, 83 and has size 3. The list contains 5, 10. vector::at checks the index and throws on an invalid index; operator[] requires the caller to provide a valid index. A list has no indexing operator.
Size and capacity
size is the number of constructed elements. capacity is the number a vector can hold without reallocating. reserve changes capacity without creating elements. resize changes the number of elements. Calling reserve(10) does not make indices 0 through 9 valid if size is still zero.
Iterator and reference invalidation
When vector growth reallocates storage, existing pointers, references and iterators into that vector become invalid. Erasing elements can invalidate positions at or after the erased element. Reacquire access after operations that may invalidate it.
List insertion generally preserves existing element iterators and references; erasure invalidates those to the erased element. However, finding the insertion location can still require linear traversal, and separate node allocations add overhead. Compare the whole workload rather than one isolated operation.
Practice
- Append five marks to a vector, compute the total with a range loop and handle an empty vector before computing an average.
- Call reserve on an empty vector, then inspect size. It remains zero.
- Use at with an invalid index inside a try/catch after studying exceptions.
- Explain why storing a pointer to marks[0] and then repeatedly pushing elements can be unsafe.
हिन्दी संकेत: reserve storage तैयार करता है; resize elements बनाता या हटाता है। दोनों को एक जैसा न समझें।