If you have worked with the C++ STL library, you have definitely encountered the error “Vector subscript out of range.” This occurs when attempting to access an element in a std::vector using an invalid index. This often leads to undefined behavior, crashes, or runtime errors.
In this article, we will discuss the causes of this error and effective ways to fix it.
What Causes ‘Vector Subscript Out of Range’ Error?
When working with C++ vectors, you might encounter the ‘Vector Subscript Out of Range’ error. This runtime error occurs when accessing elements beyond the vector’s size, leading to undefined behavior. Let’s see some scenario where you will encounter vector index out of bounds issue.
1. Accessing an Empty Vector:
When you declare a std::vector without adding elements, it remains empty. Attempting to access an element using operator[] will result in undefined behavior.
#include <iostream> #include <vector> int main() { std::vector<int> v; //Accessing an empty vector //lead undefine behaviour v[0] = 27; return 0; }
Solution: Use push_back() or resize() to allocate space.
v.push_back(27); // Adds an element // OR v.resize(1); v[0] = 27; // Now valid
2. Accessing an Index Greater Than size() – 1
If you attempt to access an index beyond the allocated size, the program exhibits undefined behavior.
#include <iostream> #include <vector> int main() { std::vector<int> v = {1, 2, 3}; std::cout << v[5]; // Error: Index out of range return 0; }
Solution: Use at() instead of operator[].
// Throws std::out_of_range exception std::cout << v.at(5);
3. Using operator[] Instead of push_back()
If the vector has not been resized, operator[] cannot be used to insert new elements.
#include <iostream> #include <vector> int main() { std::vector<int> vec(3); //Out-of-range access! Index 3 does not exist (valid: 0 to 2) vec[3] = 50; std::cout << vec[3] << std::endl; return 0; }
Solution: Use push_back() or resize().
v.push_back(100); // Works correctly // OR // Expands vector to accommodate 4 elements v.resize(4); v[0] = 100; //Ok now
Practices to Avoid ‘Vector Subscript Out of Range’ Error:
1. Always Check Vector Size Before Accessing Elements:
if (!v.empty()) { std::cout << v[0]; }
2. Use at() Instead of operator[] for Safer Access:
try { std::cout << v.at(5); // Throws exception if out of range } catch (const std::out_of_range& e) { std::cerr << "Error: " << e.what() << std::endl; }
3. Use Iterators for Safe Traversal:
for (auto it = v.begin(); it != v.end(); ++it) { std::cout << *it << " "; }
4. Use resize() Before Assigning Values:
v.resize(10); // Safe because memory is allocated v[5] = 20;
5. Use assign():
You can use assign() when you want to initialize or overwrite elements in a std::vector.
#include <iostream> #include <vector> int main() { std::vector<int> vec; //Resizes vector to 4 elements, initializing all to 0 vec.assign(4, 0); //Now safe to access index 3 vec[3] = 50; std::cout << vec[3] << std::endl; return 0; }
6 Use std::vector initializer list:
Use proper initializer list.