Ошибка vector subscript out of range

When I try to run this program I get an error that halts the program and says, «Vector subscript out of range»

Any idea what I’m doing wrong?

#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;

//(int argc, char* argv[]
int main()
{
    fstream bookread("test.txt");
    vector<string> words;

    bookread.open("test.txt");
    if(bookread.is_open()){
        cout << "opening textfile";
        while(bookread.good()){
            string input;
            //getline(bookread, input);
            bookread>>input;
            //string cleanedWord=preprocess(input);         
            //char first=cleanedWord[0];
            //if(first<=*/
            //cout << "getting words";
            //getWords(words, input);
        }
    }
    cout << "all done";

    words[0];

getchar();
}

Gregor Brandt's user avatar

asked Mar 1, 2011 at 23:10

charli's user avatar

1

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.

answered Mar 1, 2011 at 23:14

Axel Gneiting's user avatar

6

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.

answered Mar 1, 2011 at 23:14

dma's user avatar

dmadma

1,73810 silver badges25 bronze badges

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.

Try this:

for(vector<string>::const_iterator it=words.begin(), end=words.end(); it!=end; ++it){
  cout << *it << ' ';
}

answered Mar 1, 2011 at 23:27

quamrana's user avatar

quamranaquamrana

37.5k12 gold badges52 silver badges71 bronze badges

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.

answered Mar 1, 2011 at 23:49

user640121's user avatar

user640121user640121

1111 gold badge1 silver badge5 bronze badges

The Vector subscript out-of-range error message occurs when there is an issue in the index range and when the vector cannot be accessed. In this article, the reader will understand the reasons behind this error and which methods are best to resolve them. First, let’s begin with the causes!vector subscript out of range

Contents

  • Why Is the Error Vector Subscript Out of Range Message Occurring?
    • – Indexing Issue
    • – Syntax Errors
    • – The Wrong Loop Is Made
  • How To Remove the Vector Subscript Out of Range Error Message?
    • – Correct the Syntax Errors
    • – Resolve the Indexing Issue by Using the Pushback Function
    • – Correct the Loop Error
    • – Use the Assert(Boolean) Method
  • Conclusion

Why Is the Error Vector Subscript Out of Range Message Occurring?

The Vector subscript out-of-range error occurs because the programmer attempts to access a vector element using a subscript but is outside the index range. Moreover, an “out of range” error is not a segmentation fault, also called core dumped, all the time.

There are other reasons that cause this error to arise. These are listed and explained below.

  • Indexing issue.
  • Syntax errors.
  • The wrong loop is made.

Using the operator[] function to access an index that is out of bounds will also result in undefined behavior.

– Indexing Issue

While making a loop in the program, the index range can be coded wrong. Thus, when the programmer tries to access a vector element, it will be out of the index range. Thus, the program will show an error.

Furthermore, vectors are used to dynamically store data types of similar elements, also called dynamic arrays. Additionally, vectors can be iterated using index sizes from 0 to N – 1, where N = vector’s size. Do note that the size() function gives the number of elements of the vector. There are two main syntaxes for index sizes:

  1. for (int a = 0; a < vec.size(); a++) { cout<<vec[a]<<endl; }
  2. for (auto it : vec) { cout<<*it<<endl; }

Moreover, while iterating, the programmer might update/ delete/ modify/ resize the vector’s size, resulting in indexing and the number of elements changing. Thus, in some scenarios, the code works fine, although the programmers have any one of the above operations. However, codes mostly give subscription out-of-range errors, irrespective of the compiler/IDE is using

For example:

#include<iostream>

#include<vector>

using namespace std;

int main()

{

vector<int> v;

for (int d = 1; d <= 10; ++d)

v.push_back(d);

for (int c = 10; c > 0; –c)

cout << v.at(c) << ” “;

return 0;

}

Explanation:

In the above program, the programmer inserted only ten elements indexing from 0 to 9 but tried to access the tenth indexed number in the second loop. Thus, this causes an error and becomes a reason for indexing issues.

– Syntax Errors

Syntax errors are the driving factor behind the occurrence of vector errors. If the programmer uses a wrong function while coding or accidentally makes a wrong loop as a typo error, the syntax error will occur. Some common vector errors that occur due to syntax errors are listed below:Vector Subscript Out of Range Causes

  • Vector subscript out of range visual studio.
  • Vector subscript out of range line 1566.
  • Vector subscript out of range for loop.
  • Vector subscript out of range apogee.

– The Wrong Loop Is Made

When a programmer makes a wrong internal loop in a program, the vector element will not be accessible, and eventually, the error message will arise. Usually, the wrong loops give an error of “loop is out of range”. Let’s see an example below.

For Example:

#include<iostream>

#include<vector>

using namespace std;

int main()

{

vector<int> v;

for (int z = 1; z <= 10; ++z)

v.push_back(z);

for (int e = 10; e > 0; –e)

cout << v.at(e) << ” “;

return 0;

}

Explanation:

As it is seen in the above program, the loop is out of range because they are clashing and are not equal to each other. Thus, its output will launch an error message of, Vector subscript out of range.

How To Remove the Vector Subscript Out of Range Error Message?

In order to remove the “vector subscript out of range” error message, the programmer should go through some checks, such as syntaxes should be correct, check the index ranges of the loops, and many more. If there’s an index range issue, you can fix it by passing the pushback function.



– Correct the Syntax Errors

The programmers must resolve the programs’ syntax errors to eliminate the exceptional error. They can do this manually and through software specially designed for this purpose. By correcting syntax errors, the programmers can get rid of many Vector errors, such as:

  • Vector subscript out of range line 1733.
  • Vector subscript out of range line 1501.
  • Vector subscript out of range line 1475.
  • Invalid vector subscript c++.

– Resolve the Indexing Issue by Using the Pushback Function

In order to remove the error message, the programmer has to solve the index issue created in the loops of the program. A common method to use is the Pushback() function. The programmer should try to find the indexing when they are iterating over the vectors and ensure to check their sizes after every operation applied to them. The programmer can also iterator “*it” to access them.

Wrong example:

#include<iostream>

#include<vector>

using namespace std;

int main()

{

vector<int> k;

for (int k = 1; k <= 10; ++k)

v.push_back(k);

for (int o = 10; o > 0; –o)

cout << v.at(o) << ” “;

return 0;

}

Correct example:

#include<iostream>

#include<vector>

using namespace std;

int main()

{

vector<int> v;

for (int k = 1; k <= 10; ++k)

v.push_back(k);

for (int o=0; o<=10; o++){

cout << v.at(o) << ” k , “;

if(o==8)

v.erase(v.begin()+8);

}

return 0;

}

Explanation:

The programmer will get the error message in the above “wrong example” because they didn’t use the correct index ranges. In that program, the programmer set a vector size of ten and used an erase operation on the vector, “if (o==8)”. This function will result in a vector size of nine. Therefore, the output will contain the “subscript out-of-range” exception error message when the iteration goes to number ten.

However, in the correct example, the programmer has used the v.erase(v.begin()+8) function. It is a debugging tool the programmer uses on a vector to remove index range issues. Thus, the error message will be resolved.

– Correct the Loop Error

Another method to remove the error message is by checking a program’s internal loops and noticing if they are working fine after every operation that is applied to them. Let’s see two examples with their explanations below.Vector Subscript Out of Range Fixes

Wrong Example:

#include “stdafx.h”

#include “iostream”

#include “vector”

using namespace std;

int _tmain(int argc, _TCHAR * argv[])

{

vector<int> v;

cout << “Hello Europe” << endl;

cout << “Size of the vector is: ” << v.size() << endl;

for (int k = 1; k <= 10; ++k)

{

v.push_back(k);

}

cout << “size of the vector: ” << v.size() << endl;

for (int b = 10; b > 0; –b)

{

cout << v[b];

}

return 0;

}

Explanation:

The above example fills the vector with ten values in the first “for loop”, which will function in t=a normal way. However, in the second “for loop”, the programmer wants the vector elements to be printed. Therefore, the output will occur till the first cout statement before the b loop gives an error of vector subscript out of range. Given below is the correct example of the loop program.

Correct example:

#include “stdafx.h”

#include “iostream”

#include “vector”

using namespace std;

int _tmain(int argc, _TCHAR * argv[])

{

vector<int> v;

cout << “Hello Europe” << endl;

cout << “Size of the vector is: ” << v.size() << endl;

for (int k = 0; k < 10; ++k)

{

v.push_back(k);

}

cout << “size of the vector: ” << v.size() << endl;

for (int b = 9; b >= 0; –b)

{

cout << v[b];

}

return 0;

}

Explanation:

In this program, the error is removed because we corrected the loop range. Moreover, generally, it is better to consider index ranges starting from zero, so the programmer changed their first loop, which starts from zero.

– Use the Assert(Boolean) Method

By default, the debug assertion method only works in debug builds or programs. This will eliminate the undefined error message. The programmers should opt for the Trace.Assert method if they want to do assertions in release builds. Moreover, if the syntax for an assertion is wrong, the “assertion failed” message will occur.

Furthermore, the Assert(Boolean) method is used for identifying logical errors during program development. Additionally, assert evaluates the condition, and if the result is false, it sends a failure notification to the Listeners collection. However, this program’s behavior can be customized by adding a “TraceListener” or removing one from the Listeners collection.

Working Mechanism Explained:

When the program is running in user interface mode, a message box displaying the call stack together with file and line numbers is displayed. Three buttons are displayed in the message box: Abort, Retry, and Ignore. The application is closed when the programmer uses the Abort button. If the application is running in a debugger, clicking Retry will direct the programmer to the code inside; otherwise, it will offer to launch a debugger. The next line of code is executed when Ignore is clicked.

Conclusion

After reading this guide, we believe that you would’ve gained knowledge about the Vector subscript out-of-range error message and what they can do to remove it from the program. The main points from this article are:

  • Since the “std::vector::operator[]” function does not check for limits, it will not throw an exception when an improper index is passed in.
  • To throw an exception, you should use the std::vector::at() function to check the boundaries.
  • If there are less than two elements in the index, the index[2] function activates the undefined behavior.

The readers can now resolve the vector errors by using the information given in this guide.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Антон219

0 / 0 / 0

Регистрация: 09.06.2013

Сообщений: 72

1

23.06.2014, 05:43. Показов 20825. Ответов 15

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Привет, друзья, у меня следующая проблема:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
if (!MeteorVec.empty())
            {
                for (int i = 0; i < MeteorVec.size(); i++)
                {
                    MeteorVec[i]->Moove();
                    if (RectCrossesRect (bullet->borderRect, MeteorVec[i]->borderRect))
                    {
                        MeteorVec[i]->GetsDestroyed(hwnd);
                        bullet->Dissapears();
                        Meteors* p = MeteorVec[i];
                        MeteorVec[i] = MeteorVec.back();
                        MeteorVec.pop_back();
                        delete p;
                    }
                    if (RectCrossesRect (ship->borderRect, MeteorVec[i]->borderRect) && ship->exists)
                    {
                        ship->GetsDestroyed();
                        SetTimer(hwnd, 5, 1000, NULL);
                        Meteors* p = MeteorVec[i];
                        MeteorVec[i] = MeteorVec.back();
                        MeteorVec.pop_back();
                        delete p;
                    }           
                    if (MeteorVec[i]->position.x < 30)
                    {
                        Meteors* p = MeteorVec[i];
                        MeteorVec[i] = MeteorVec.back();
                        MeteorVec.pop_back();
                        delete p;
                    }
                }
            }

все выполняется внутри таймера, MeteorVec — это вектор. Так вот, иногда вылезает ошибка: «vector subscript out of range», может я просто по глупости не вижу очевидного, но никак не могу вкурить, в какой момент он может вылезти за пределы? И как исправить?



0



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

23.06.2014, 06:19

2

Предположим, что в одном из первых if() происходит удаление последнего элемента вектора (MeteorVec.pop_back()), вектор пуст, но в следующем if() будет обращение по индексу к пустому вектору (например, if (MeteorVec[i]->position.x < 30)), что и вызовет ошибку. После каждого удаления нужно проверять вектор на пустоту, и выполнять нужные действия, в зависимости от результата проверки.



2



Ilot

Эксперт по математике/физикеЭксперт С++

2013 / 1342 / 382

Регистрация: 16.05.2013

Сообщений: 3,463

Записей в блоге: 6

23.06.2014, 09:18

3

Цитата
Сообщение от alsav22
Посмотреть сообщение

Предположим, что в одном из первых if() происходит удаление последнего элемента вектора (MeteorVec.pop_back()), вектор пуст, но в следующем if() будет обращение по индексу к пустому вектору (например, if (MeteorVec[i]->position.x < 30)), что и вызовет ошибку.

Не думаю:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
struct sd {
  int a;
  sd(int A): a(A)
  {}
};
int main() {
  std::vector<sd> coll;
  //coll.reserve(2);
  coll.push_back(11);
  coll.pop_back();
  coll.pop_back();
  coll.pop_back();
  coll.pop_back();
  std::cout << coll[59].a << std::endl;
 
  return 0;
}

Компилится без проблем и кидает искючение только если векторе не выделена память для элементов. Так что кто кидает исключение вопрос открытый.
Антон219, посмотрите в своей реализации кто может кидать такое исключение.



1



Croessmah

Неэпический

17815 / 10586 / 2044

Регистрация: 27.09.2012

Сообщений: 26,631

Записей в блоге: 1

23.06.2014, 11:08

4

Цитата
Сообщение от Ilot
Посмотреть сообщение

Не думаю:

Читаем тут http://www.cplusplus.com/refer… /pop_back/

If the container is not empty, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.

Так же, если контейнер окажется пустым, то

C++
1
MeteorVec[i] = MeteorVec.back();

будет тоже не здорово себя вести



1



Ilot

Эксперт по математике/физикеЭксперт С++

2013 / 1342 / 382

Регистрация: 16.05.2013

Сообщений: 3,463

Записей в блоге: 6

23.06.2014, 11:35

5

Croessmah, так я же и говорю, что пусть смотрит в своей реализации. Так как в GCC эти методы объявлены так:

C++
1
2
3
4
5
6
7
8
9
10
11
      void
      pop_back() _GLIBCXX_NOEXCEPT
      {
    ...
      }
      reference
      back() _GLIBCXX_NOEXCEPT
      { return *(end() - 1); }
      const_reference
      back() const _GLIBCXX_NOEXCEPT
      { return *(end() - 1); }

Что как бы намекает, что исключение кидать они не могут.



1



alsav22

5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

23.06.2014, 18:33

6

Цитата
Сообщение от Ilot
Посмотреть сообщение

Так что кто кидает исключение вопрос открытый.

Вот код и результат работы:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>
using namespace std;
 
int main() 
{
    vector<int> coll;
    coll.push_back(11);
    coll.pop_back();
    int i = 1;
    if (coll[i] == 3)
        cout << coll[i] << endl;
    else 
        cout << "No!" << endl;
 
    system("pause");
    return 0;
}

Миниатюры

Vector subscript out of range
 



1



Антон219

0 / 0 / 0

Регистрация: 09.06.2013

Сообщений: 72

23.06.2014, 21:42

 [ТС]

7

Вроде исправил!)) Как я понимаю, проблема могла быть, если один из блоков if() пытался обращаться к уже несуществующему элементу. Я поставил цикл for() один и тот же перед каждым блоком if():

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
for (int i = 0; i < MeteorVec.size(); i++)
                {
                    MeteorVec[i]->Moove();
                    if (RectCrossesRect (bullet->borderRect, MeteorVec[i]->borderRect))
                    {
                        MeteorVec[i]->GetsDestroyed(hwnd);
                        bullet->Dissapears();
                        if (i < MeteorVec.size())
                        {
                            delete MeteorVec[i];
                            MeteorVec.erase(MeteorVec.begin() + i);
                        }
                    }
                }
                for (int i = 0; i < MeteorVec.size(); i++)
                {
                    if (RectCrossesRect (ship->borderRect, MeteorVec[i]->borderRect) && ship->exists)
                    {
                        ship->GetsDestroyed();
                        SetTimer(hwnd, 5, 1000, NULL);
                        if (i < MeteorVec.size())
                        {
                            delete MeteorVec[i];
                            MeteorVec.erase(MeteorVec.begin() + i);
                        }
                    }   
                }
                for (int i = 0; i < MeteorVec.size(); i++)
                {
                    if (MeteorVec[i]->position.x < 30)
                    {
                        if (i < MeteorVec.size())
                        {
                            delete MeteorVec[i];
                            MeteorVec.erase(MeteorVec.begin() + i);
                        }
                    }
                }

Удаление тоже изменил, но даже с проверкой if (i < MeteorVec.size()) это не помогло. Помогло только добавление for.
Спасибо за помощь!)
И еще ламерский вопрос: Ilot, как мне понять, по моей реализации, что кидает исключение? Что вообще может его кидать?



0



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

23.06.2014, 21:57

8

Цитата
Сообщение от Антон219
Посмотреть сообщение

как мне понять, по моей реализации, что кидает исключение? Что вообще может его кидать?

Берёте отладчик и смотрите, в каком месте кода возникает исключение.



2



What a waste!

1607 / 1299 / 180

Регистрация: 21.04.2012

Сообщений: 2,727

23.06.2014, 23:05

9

Цитата
Сообщение от alsav22
Посмотреть сообщение

как мне понять, по моей реализации, что кидает исключение? Что вообще может его кидать?

Вообще есть стандарт языка, там всё поведение специфицировано, в кишки своей реализации лезть не обязательно. Справку можно посмотреть например здесь или тут.



1



Эксперт по математике/физикеЭксперт С++

2013 / 1342 / 382

Регистрация: 16.05.2013

Сообщений: 3,463

Записей в блоге: 6

24.06.2014, 08:15

10

alsav22, как видно у вас кидает исключение отладчик, т.е. среда. Как я и говорил. Вы не пробывали запустить релиз сборку?



1



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

24.06.2014, 08:23

11

Цитата
Сообщение от Ilot
Посмотреть сообщение

как видно у вас кидает исключение отладчик, т.е. среда. Как я и говорил.

Отладчику можно? Не обращать внимания? Или о чём речть?



1



Эксперт по математике/физикеЭксперт С++

2013 / 1342 / 382

Регистрация: 16.05.2013

Сообщений: 3,463

Записей в блоге: 6

24.06.2014, 08:28

12

Цитата
Сообщение от alsav22
Посмотреть сообщение

Или о чём речть?

Цитата
Сообщение от Ilot
Посмотреть сообщение

Антон219, посмотрите в своей реализации кто может кидать такое исключение.

Я уже писал о том, что подобное поведение не является стандартом, а определяется реализацией и ваш пример вместе с моим собственно и подтвердил эти слова.



1



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

24.06.2014, 08:34

13

Понятно.



1



1 / 1 / 0

Регистрация: 02.08.2022

Сообщений: 9

05.08.2022, 14:27

14

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

int main() {
int n, c = 0;
cin >> n;
vector <int> a;

//ввод
cin >> a[0];
for (int i = 1; i < n; i++) {

if (a[i] > a[i-1]){ c++; }
cin >> a[i];
}

cout << c;

return 0;
}



0



4023 / 3280 / 920

Регистрация: 25.03.2012

Сообщений: 12,270

Записей в блоге: 1

05.08.2022, 15:34

15

Ilya_2009, и чё? Ну говнокод, ну бывает. Зачем он в теме про Vector subscript out of range? Тем более в такой старой теме.



0



SmallEvil

05.08.2022, 16:03


    Vector subscript out of range

Не по теме:

Kuzia domovenok, наверное отрабатывает гроши что заплатили ранее.
Потому как сейчас нет смысла троллить на забытом задворке старого сарая.. Но оно все равно продолжает.
Се ля ви.



0



Когда программа C++ выдает ошибку выхода за диапазон индекса, то индекс, используемый для доступа к элементу вектора, находится за пределами диапазона векторных индексов. Однако это зависит от компилятора. С компилятором g++ для Ubuntu, когда нижний индекс выходит за пределы диапазона, возвращается значение по умолчанию или какое-либо другое значение или считается, что оно находится в ячейке. Это происходит только тогда, когда вектор уже определен с некоторыми элементами. С компилятором g++, когда вектор объявлен без какого-либо элемента и предпринимается попытка доступа к связанной ячейке памяти (без какого-либо элемента в нем), используя любое целое число нижнего индекса (даже 0), компилятор g++ выдает ошибку: «Ошибка сегментации (ядро сброшен)».

Прежде чем продолжить чтение, необходимо напомнить следующее: Нижний индекс — это индекс в квадратных скобках для имени вектора. Этот индекс используется для ссылки на элемент вектора. Каждый индекс относится к определенному элементу (значению). Подсчет индекса начинается с 0 и заканчивается на vectorSize – 1. Итак, если вектор имеет 10 элементов, первый элемент имеет индекс 0, а десятый элемент имеет индекс 9. Использование индекса 10 в векторе для чтения или изменения значения элемента с индексом 10, который не существует, должно вывести сообщение об ошибке вне допустимого диапазона. Однако с компилятором g++, если вектор определен (память, выделенная для элементов, даже если они являются элементами по умолчанию), когда используется индекс за пределами диапазона, возвращается значение по умолчанию типа элемента вектора или какое-либо другое значение типа (или должно быть измененный).

Иллюстрация вне диапазона

Рассмотрим следующую таблицу:

А Б С Д Е Ф грамм ЧАС я Дж
-2 -1 0 1 2 3 4 5 6 7 8 9 10 11

В первой строке показано, как было произведено десять выделений памяти для 10 символов. Под символами в таблице, во второй строке, находятся правильные нижние индексы (индексы). Использование нижнего индекса -1, -2, -3 и т. д. должно привести к выдаче ошибки вне допустимого диапазона. Использование нижнего индекса 10, 11, 12 и т. д. также должно приводить к выдаче ошибки вне допустимого диапазона.

В этой статье показаны ситуации, в которых выдаются ошибки вне допустимого диапазона. Компилятор, используемый для примеров кода в этой статье, — это компилятор g++ для Ubuntu. Не забудьте включить в программу векторную библиотеку, для любого компилятора.

Ошибка вне диапазона для заданного вектора

Определенный вектор — это вектор, для которого выделена память для начальных элементов. Значения могут быть значениями по умолчанию или практическими значениями для типа векторного элемента. Объявленный вектор без какой-либо формы инициализации не является определенным вектором. Для такого вектора нет выделения памяти для любого элемента вектора. Такой вектор пуст.

Компилятор G++ для Ubuntu

Предположим, что в векторе десять элементов; нередкая ошибка людей, не имеющих опыта программирования, заключается в том, что они обращаются к десятому элементу с индексом 10. К нему следует обращаться с индексом 9, так как отсчет индекса начинается с 0. Рассмотрим следующую программу с 10 элементами в векторе и доступом к десятому элементу с индексом 10:

#включать
#включать
используя пространство имен std;

инт главный()
{
векторvtr ={«А»,‘Б’,‘С’,‘Д’,‘Э’,‘Ф’,‘ГРАММ’,‘ЧАС’,‘Я’,‘Дж’};
уголь ч = ВТР[10];//оператор ошибки
cout<<ч<<конец;
возврат0;
}

Эта программа с компилятором g++ для Ubuntu выдает ,», что означает отсутствие символа (без пробела). Символ ничего — это символ по умолчанию для символов в C++. Для этого вектора нет одиннадцатого члена. Итак, второй оператор — это оператор ошибки, который не обнаруживается компилятором g++. С компилятором g++ он по-прежнему не определяется во время выполнения, и программа работает неправильно.

Некоторые другие компиляторы

Когда вышеуказанная программа используется с некоторыми другими компиляторами, оператор ошибки обнаруживается во время выполнения, и создается исключение с сообщением об ошибке, выдаваемым на выходе. Однако ошибка по-прежнему не обнаруживается во время компиляции.

Рассмотрим следующее объявление:

вектор<уголь> ВТР(10);

Это может не выглядеть как определение, но это определение. Имеется десять ячеек памяти для десяти векторных элементов со значением символа по умолчанию.

Ошибка вне диапазона для неопределенного вектора

Объявленный вектор без какой-либо формы инициализации не является определенным вектором. Для такого вектора нет распределения ни для одного элемента вектора. Такой вектор пуст.

Компилятор G++ для Ubuntu

Когда объявленный вектор не имеет инициализации (или не имеет значений по умолчанию), использование нижнего индекса неприменимо к вектору при доступе к любому элементу вектора, поскольку он отсутствует. Даже нулевой индекс нельзя использовать для доступа к первому элементу, которого нет. В следующей программе делается попытка доступа к первому элементу, которого нет:

#включать
#включать
используя пространство имен std;

инт главный()
{
векторvtr;
уголь ч = ВТР[0];//оператор ошибки
cout<<ч<<конец;
возврат0;
}

Первый оператор в основной функции объявляет вектор без какой-либо области памяти для любого из его элементов. Это утверждение не является определением. Второй оператор пытается прочитать значение по индексу 0. Это оператор ошибки, потому что вектор не имеет элемента, и поэтому ни один элемент не присутствует ни в каком нулевом индексе.

С компилятором g++ программа успешно компилируется, но во время выполнения, когда достигается второй оператор в основной функции, программа останавливается и выдается следующее сообщение об ошибке:

Ошибка сегментации (дамп ядра)

Некоторые другие компиляторы

Выполнение вышеуказанной программы в других компиляторах и отслеживание соответствующих сообщений об ошибках оставляется читателю в качестве упражнения.

Вывод

Ошибка выхода индекса вектора за диапазон возникает при попытке доступа к элементу вектора с использованием индекса, который находится за пределами диапазона индекса. Ошибка «вне диапазона» — это не то же самое, что ошибка сегментации (сброс ядра) все время.

Prerequisites:

  • Access elements from a vector
  • Change a particular element

Introduction:

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).

 Syntax:

  1. for (int i = 0; i < vec.size(); i++) { cout<<vec[i]<<endl; }
  2. for (auto it : vec) { cout<<*it<<endl; }

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 =>

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

int main()
{
    vector<int> v;
    for (int i = 1; i <= 10; ++i)
        v.push_back(i);

    for (int j = 10; j > 0; --j)
        cout << v.at(j) << " ";
    return 0;
}

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 =>

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

int main()
{
    vector<int> v;
    for (int i = 1; i <= 10; ++i)
        v.push_back(i);

    for (int j=0; j<=10; j++){
        cout << v.at(j) << " k , ";
        if(j==8)
            v.erase(v.begin()+8);
    }
    return 0;
}

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.

Points to be noted:

  1. Since “std::vector::operator[]” doesn’t check for limits, it won’t throw an exception if an improper index is passed in. Using operator[] to access an index that is out of bounds results in undefined behavior.
  2. If you wish to throw an exception, use std::vector::at() to check the boundaries. If an invalid index is passed in, it will throw a std::out of range exception.
  3. Ex: If there are fewer than two elements in the index, the index[2] activates undefined behavior, which means the compiler can do whatever it wants. It is not necessary to throw an exception in this case. If you want an exception, use index.at(2), which is designed or intended.

Понравилась статья? Поделить с друзьями:
  • Ошибка vector does not name a type
  • Ошибка vds basic provider что это
  • Ошибка vdm форд мондео 4
  • Ошибка vdc off инфинити что это такое
  • Ошибка vdc off инфинити g25