C vector subscript out of range error
vector subscript out of range error is caused by accessing indexes that exceed the valid range of vector. It is common in cases where empty vector access, index equals size(), reverse order traversal unsigned type wrapping, etc.; 1. Before accessing empty vector, you should check empty() or make sure that elements have been inserted; 2. The loop conditions should use i 0;) to avoid cross-border; 4. Before using, you should call resize() or push_back() to initialize elements; exceptions can be triggered to assist debugging through at(), use range for loop to avoid index errors, and pay attention to size() Returns unsigned types to prevent implicit conversion problems, and effectively avoids the error by ensuring that the previous access index
vector subscript out of range
is a common runtime error when using std::vector
in C and usually occurs where you are trying to access a location outside the range of the valid index of vector. This error will be triggered in debug versions (Debug mode), especially in compiler environments such as Visual Studio, because the standard library will perform boundary checks.

Why does this error occur?
When you access an element using vector[i]
or vector.at(i)
:
-
vector[i]
: No boundaries are checked (there will be no errors in Release mode, but the behavior is undefined) -
vector.at(i)
: Will perform bounds checking . Ifi >= vector.size()
,std::out_of_range
exception will be thrown - In Debug mode , even if
operator[]
is used, many compilers (such as MSVC) will automatically insert bounds checks, triggering the "vector subscript out of range" assertion
Common error scenarios
1. Access the element of the empty vector
std::vector<int> vec; int x = vec[0]; // Error! vector is empty
2. Use the wrong index (such as size() as the index)
std::vector<int> vec = {10, 20, 30}; for (int i = 0; i <= vec.size(); i ) { std::cout << vec[i] << " "; // When i == vec.size() passes the boundary! }
Note:
vec.size()
returns3
, but the valid index is0, 1, 2
.i <= vec.size()
will causei=3
to cross the boundary.
3. Loop conditions are written incorrectly (commonly in reverse order traversal)
for (int i = vec.size() - 1; i >= 0; i--) { // No problem under normal circumstances}
But if vec
is empty, vec.size() - 1
will become the maximum value of size_t
(because size()
is an unsigned type), resulting in infinite loops or cross-borders.
Correction method:

for (int i = static_cast<int>(vec.size()) - 1; i >= 0; i--) { std::cout << vec[i] << " "; }
Or use unsigned type-safe handling:
for (size_t i = vec.size(); i-- > 0; ) { std::cout << vec[i] << " "; }
4. Forgot to initialize or push_back in advance
std::vector<int> vec; vec.resize(5); // or vec.push_back(...) If you do not do this, the following access will error vec[0] = 10; // Only after resize or push_back can you access it
How to avoid and debug?
✅ Use .at()
for debugging
try { std::cout << vec.at(100) << std::endl; } catch (const std::out_of_range& e) { std::cerr << "Out of the line!" << e.what() << std::endl; }
Helps position problems, but should not be used in performance-sensitive occasions.
✅ Make sure the index is legal
if (i < vec.size()) { std::cout << vec[i]; } else { std::cout << "Index transboundary"; }
✅ Use range for loop (recommended)
for (const auto& item : vec) { std::cout << item << " "; }
Avoid index errors completely.
✅ Pay attention to the type of size()
vec.size()
returns size_t
(unsigned integer), and it is prone to errors when mixed with signed integers:
for (int i = 0; i < static_cast<int>(vec.size()); i ) { ... }
Or use size_t i
uniformly.
Summarize
question | Solution |
---|---|
Access to empty vector | Check vec.empty() first or make sure the element has been added |
Index equals size() | The loop condition should be i
|
Reverse order traversal across boundaries | Be careful size()-1 when swinging back when empty container |
Report an error under Debug, Release does not report | Debug has bounds checking, Release does not (but still undefined behavior) |
Basically this error is "You visited a location that does not exist". It can be avoided by confirming index before accessing and <code>vector
is not empty.
? Small suggestions: Try to use
at()
or enable Debug check during development, and replace it with[]
before going online to improve performance. Not complicated but easy to ignore.
The above is the detailed content of C vector subscript out of range error. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

There are many initialization methods in C, which are suitable for different scenarios. 1. Basic variable initialization includes assignment initialization (inta=5;), construction initialization (inta(5);) and list initialization (inta{5};), where list initialization is more stringent and recommended; 2. Class member initialization can be assigned through constructor body or member initialization list (MyClass(intval):x(val){}), which is more efficient and suitable for const and reference members. C 11 also supports direct initialization within the class; 3. Array and container initialization can be used in traditional mode or C 11's std::array and std::vector, support list initialization and improve security; 4. Default initialization

Object slice refers to the phenomenon that only part of the base class data is copied when assigning or passing a derived class object to a base class object, resulting in the loss of new members of the derived class. 1. Object slices occur in containers that directly assign values, pass parameters by value, or store polymorphic objects in storage base classes; 2. The consequences include data loss, abnormal behavior and difficult to debug; 3. Avoiding methods include passing polymorphic objects using pointers or references, or using smart pointers to manage the object life cycle.

RAII is an important technology used in resource management in C. Its core lies in automatically managing resources through the object life cycle. Its core idea is: resources are acquired at construction time and released at destruction, thereby avoiding leakage problems caused by manual release. For example, when there is no RAII, the file operation requires manually calling fclose. If there is an error in the middle or return in advance, you may forget to close the file; and after using RAII, such as the FileHandle class encapsulates the file operation, the destructor will be automatically called after leaving the scope to release the resource. 1.RAII is used in lock management (such as std::lock_guard), 2. Memory management (such as std::unique_ptr), 3. Database and network connection management, etc.

To determine whether std::optional has a value, you can use the has_value() method or directly judge in the if statement; when returning a result that may be empty, it is recommended to use std::optional to avoid null pointers and exceptions; it should not be abused, and Boolean return values or independent bool variables are more suitable in some scenarios; the initialization methods are diverse, but you need to pay attention to using reset() to clear the value, and pay attention to the life cycle and construction behavior.

There are four common methods to obtain the first element of std::vector: 1. Use the front() method to ensure that the vector is not empty, has clear semantics and is recommended for daily use; 2. Use the subscript [0], and it also needs to be judged empty, with the performance comparable to front() but slightly weaker semantics; 3. Use *begin(), which is suitable for generic programming and STL algorithms; 4. Use at(0), without manually null judgment, but low performance, and throw exceptions when crossing the boundary, which is suitable for debugging or exception handling; the best practice is to call empty() first to check whether it is empty, and then use the front() method to obtain the first element to avoid undefined behavior.

Pure virtual functions are the key mechanisms used in C to define abstract classes and interfaces, and their core role is to force derived classes to implement specific methods. 1. The pure virtual function is declared through virtualvoidfunc()=0; and the implementation is not provided, making the class an abstract class and cannot be instantiated; 2. It is used to simulate the interface to ensure that the subclass must rewrite the method, such as the draw() of the Shape base class in the graphics library; 3. Supports runtime polymorphism, allowing the base class pointer to call the implementation of different subclasses; 4. Although the abstract class cannot create objects, it can contain constructors, member variables and implemented ordinary functions; 5. If the derived class does not fully implement all pure virtual functions, it will also become an abstract class; 6. In special cases, the pure virtual function can provide default implementation for derivation.

The destructor in C is a special member function that is automatically called when an object is out of scope or is explicitly deleted. Its main purpose is to clean up resources that an object may acquire during its life cycle, such as memory, file handles, or network connections. The destructor is automatically called in the following cases: when a local variable leaves scope, when a delete is called on the pointer, and when an external object containing the object is destructed. When defining the destructor, you need to add ~ before the class name, and there are no parameters and return values. If undefined, the compiler generates a default destructor, but does not handle dynamic memory releases. Notes include: Each class can only have one destructor and does not support overloading; it is recommended to set the destructor of the inherited class to virtual; the destructor of the derived class will be executed first and then automatically called.
