C++ vector exercises
std::vector is the workhorse of C++, but standard indexing with [] does no bounds checking, leading to silent memory corruption or segmentation faults. Pushing elements into a vector can reallocate storage and invalidate active iterators or pointers.
These exercises give you deliberate practice identifying container defects before they cause production crashes.
The vectors bugs you will meet
- operator[] does not perform bounds checks; use .at() for checked access or check .size().
- push_back() or emplace_back() can reallocate the buffer, invalidating all iterators and raw pointers.
- Erasing elements in a loop without updating the iterator causes skipped items or invalid reads.
- std::vector<bool> does not return bool&; it returns a proxy object.
The exercises
Easy
Medium
- Vector modification causes unexpected behavior in loopLogic
- Unexpected crash after function exit with lambdaScope and closure
- Unexpected behavior in integer-based list traversalLogic
- Unexpected behavior after moving vector elementsLogic
- Unexpected entries in std::map after key lookupsLogic
- Set iteration fails unexpectedly after element modificationLogic
- Vector elements not removed despite using std::removeLogic
- Unexpected program termination during threaded executionAsync and race conditions
- Iterator invalidation in vector erase loopLogic
- std::map operator[] creates unintended entriesLogic
- std::accumulate integer default truncates float sumType
- std::sort comparator violates strict weak orderingLogic
- Reverse vector with signed/unsigned comparison issueLogic
- Custom comparator missing const qualifierType
Errors you might be searching for
More JavaScript practice by topic
Questions
Why does vector [] access not throw an exception?
C++ prioritizes raw performance; operator[] is unchecked. Use .at() if you want bounds checking with std::out_of_range exceptions.