Vector subscript out of range c как исправить

от admin

Vector subscript out of range error, C++

You never insert anything into the words vector , so the line words[0]; is illegal, because it accesses the first element of it, which does not exist.

I don’t see where you’re pushing anything on to the vector. If the vector is empty, subscript 0 would be out of range.

It seems that your program never gets round to adding anything to the vector, usually done with push_back() , so at run-time words[0] produces your subscript out of range error.

You should check the size of the vector before accessing it.

Can you please attach the version of the code where you actually push_back strings on the vector. Its not possible to debug the issue unless the code on which reproduce is available for review.

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

C++ Vector Subscript Out of Range Error

Before continuing to read, there is a need to recall the following: A subscript is the index in square brackets for the vector name. This index is used to reference the element of the vector. Each index refers to a particular element (value). Index counting begins from 0 and ends at vectorSize – 1. So, if a vector has 10 elements, the first element is at index 0, and the tenth element is at index 9. Using index 10 on the vector to read or change the value of an element at index 10, which does not exist, should output an out-of-range error message. However, with the g++ compiler, as long as a vector has been defined (memory allocated for the elements, even if they are default elements), when an index outside the range is used, the default value of the vector element type or some other value of the type is returned (or is there to be changed).

Out of Range Illustration

Consider the following table:

A B C D E F G H I J
-2 -1 0 1 2 3 4 5 6 7 8 9 10 11

The first row shows how ten memory allocations have been made for 10 characters. Below the characters in the table, in the second row, are the correct subscripts (indexes). Using the subscript -1, -2, -3, etc., should result in out-of-range error issued. Using of the subscript 10, 11, 12, etc., should also result in out-of-range error issued.

This article illustrates situations in which out-of-range errors are issued. The compiler used for the code samples in this article is the g++ compiler for Ubuntu. Do not forget to include the vector library into the program, for any compiler.

Out-of-Range Error for Defined Vector

A defined vector is one for which memory has been allocated for the initial elements. The values may be default or practical values for the vector element type. A declared vector without any form of initialization is not a defined vector. For such a vector, there is no memory allocation for any vector element. Such a vector is empty.

G++ Compiler for Ubuntu

Assume that there are ten elements in a vector; a not uncommon mistake made by people who are inexperienced in programming, is to access the tenth element with the subscript of 10. It should be accessed with the subscript of 9, as index counting begins from 0. Consider the following program with 10 elements in the vector, and accessing of the tenth element with the index of 10:

#include <iostream>
#include <vector>
using namespace std ;

int main ( )
{
vectorvtr = { ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ , ‘G’ , ‘H’ , ‘I’ , ‘j’ } ;
char ch = vtr [ 10 ] ; //error statement
cout << ch << endl ;
return 0 ;
}

This program with the g++ compiler for Ubuntu gives an output of ,'', which is a character of nothing (no space). A character of nothing is the default character for characters in C++. There is no eleventh term for this vector. So, the second statement is an error statement that is not detected by the g++ compiler. With the g++ compiler, it is still not detected at runtime, and the program operates wrongly.

Some Other Compilers

When the above program is used with some other compilers, the error statement is detected at runtime, and an exception is thrown with an error message issued at the output. The error is still not detected at compile time, though.

Consider the following declaration:

Читать:
Как создать свой плейлист m3u для iptv

This may not look like a definition, but it is a definition. There are ten memory locations for the ten vector elements with the default character value.

Out-of-Range Error for Undefined Vector

A declared vector without any form of initialization is not a defined vector. For such a vector, there is no allocation for any vector element. Such a vector is empty.

G++ Compiler for Ubuntu

When a declared vector has no initialization (or has no default values), the use of subscript is not applicable to the vector in accessing any element of the vector as there is non. Even the zero index cannot be used to access the first element, which is not present. In the following program, an attempt is made to access the first element, which is not present:

#include <iostream>
#include <vector>
using namespace std ;

int main ( )
{
vectorvtr ;
char ch = vtr [ 0 ] ; //error statement
cout << ch << endl ;
return 0 ;
}

The first statement in the main function declares a vector without any memory location for any of its elements. This statement is not a definition. The second statement attempts to read the value at index 0. This is an error statement because the vector has no element, and so no element is present at any index zero.

With the g++ compiler, the program compiles successfully, but at runtime, when the second statement in the main function is reached, the program stops and the following error message is issued:

Some Other Compilers

Execution of the above program in other compilers, and noting their corresponding error messages is left as an exercise to the reader.

Conclusion

Vector subscript out-of-range error occurs when an attempt is made to access a vector element using a subscript that is outside the index range. Out-of-range error is not the same as Segmentation fault (core dumped) all the time.

Vector subscript out of range in C++ – Solution

Vectors are used to store similar data types of elements dynamically, thereby known as dynamic arrays. Vectors can be iterated using indexing from size 0 to N – 1 where N = vector’s size or using the auto keyword (similar to fresh loop).

  1. for (int i = 0; i < vec.size(); i++)
  2. for (auto it : vec)

Note: size() gives the number of elements of the vector.

Issue:

While iterating, we might update/ delete/ modify/ resize the vector’s size, which results in indexing and the number of elements. So, in some cases, your code works fine, although you have any one of the above operations. Most of the codes give subscript out of range, irrespective of compiler/IDE you are using. In this article, you are going to see 2 scenarios where you could get some insights on how to solve vector subscript out of range in C++.

Examples:

Example 1 =>

Explanation: In the above code, we insert only 10 elements indexing from 0 to 9 but accessing the 10th indexed number in the second for loop. So, this is one of the reasons regarding the indexing issue.

Resolve subscript out of range

Solution: Try to find the indexing when you are iterating over the vectors and check their sizes after every operation on them. You can also iterators (*it) for accessing them.

Example 2 =>

Explanation: In the above code, the vector is of size 10. We have made erase operation on vector if j==8, thereby resulting in the vector size as 9. But the iteration goes to 10 and outputs the “subscript out-of-range” exception.

Solution: Must be cautious while performing operations on vector and use debugging tools whenever required.

Vector subscript out of range c как исправить

Hi everyone, I have been stuck with this problem for the past two hours. The program asks the user for the names and values of their cars, stores them in tokens, and then puts the tokens into a vector. Then it prints out what the user entered. This program compiles and works up until the last part, at line 36. I don’t know if anything is wrong with the for loop. Everything prints out fine, but I get a «Debug Assertation Failed!» error at line 1234. Expression: vector subscript out of range. Is there something I’m missing here? I don’t know what’s wrong. Thanks for your help and time.

Figured it out literally 10 minutes later. The for loop should be

for (size_t i = 0; i < things.size(); ++i)

instead of what it is now. This is because cars.size() is not an int , instead it is size_t , which equals some usual «unsigned» type.

Wow, I tried that earlier, and it didn’t work, but now it suddenly does. Thanks, I was going crazy

Похожие статьи