Ошибка vector subscript out of range c

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 #include #incl...

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.1k12 gold badges55 silver badges69 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

1211 gold badge1 silver badge5 bronze badges

  • Remove From My Forums
  • Question

  • Hi,

    It’s a problem in problem. I have a C++ project that stucks during runtime (either in debug mode or not), issuing the following error window:

    Microsoft Visual C++ Debug Library

    Debug Assertion Failed!

    Program: …

    File: c:program filesmicrosoft visual studio 8vcincludevector

    Line: 756

    Expression: vector subscript out of range

    For information on how your program can cause an assertion

    Failure, see the Visual C++ documentation on asserts.

    I tried to monitor the fail point but realized that it’s not a fixed one. I’ve read in this forum about the ‘Call stack’ option (Debug + Windows + Call stack) but when I let the program run (F5), the Call stack is cleared.

    Thanks in advance for any help,

    Udi

    Forum: Which function was called before an exception is thrown?

    Yes, call stack.  Debug + Windows + Call stack

Answers

  • Well it’s clear that the subscript is out of range at more than one spot (since you’re saying its «random» where it happens). Your options are to 1. verify the application using asserts or just a watchful eye, 2. use the debugger and see where it crashes, and consider the subscript usage around that point.

  • The reserve-function makes sure that the amount of memory is available, but it doesn’t actually change the «in-use» size of the container. The resize function, on the other han, will allocate and initialize the indicated number of elements. In other words, with resize they will be ready for use, with reserve they won’t.

    You can read more about the STL containers on MSDN, or in any good C++ book. You should consider getting Effective STL by Scott Meyers. That’s a good one.

  • Forum
  • Beginners
  • vector subscript out of range

vector subscript out of range

I’ve been using visual C++ Express to work through some elementary exercises…

After I receive the message «vector subscript out of range», I am given the option to «abort», «retry», or «ignore» the message.

I tried «retrying» because I thought it would help me debug, but all I did was get really confused and become afraid my standard libraries were in the wrong place.

However…. I think that it’s as simple of a thing as having a vector subscript out of range. However…. I can’t find the problem. They all start at zero, and I didn’t know there was an upper end of a subscript range?

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// A program to count the number of times each distinct word is used in an input
#include "chapter3.h"

int main()
{
	// Read the data
	cout << "Enter the words, followed by Ctrl + Z:";
	string x;
	vector<string> words;

		// invariant: words contains all the entered words
	while (cin>>x)
	{
		words.push_back(x);
	}

	// sort the data
	sort(words.begin(),words.end());

	// create vectors for unique words and a count variable
	vector<string> distinct;
	int count = 0;
	vector<int> distinctCount;

	// test for word distinctness and store values in new vectors

	typedef vector<string>::size_type vec_sz;
	vec_sz sizeWords = words.size();
	int i = 0;

	// invariant: there are i distinct words in distinct
	while (i != sizeWords)
	{
		distinct[count] = words[i];	
		int temp = 1;
		while (words[i] == distinct[count])
		{
			distinctCount[count] = temp;
			++temp;
			++i;
		}
		++count;
	}		

	// output the data

	for (int z = 0; z != count; ++z)
	{
		cout << distinct[z] << ": " << distinctCount[z] << endl;
	}
		// hold the execution window open

	cin.clear();
	cin.sync();
	cin.ignore();

	return 0;
}

Any help finding my out of range vector subscripts would be much appreciated.
I have not included the header file, but it’s a pretty standard beginner header file.

> and I didn’t know there was an upper end of a subscript range?

There is. The inclusive range is from zero up to the size of the vector minus one.

These vectors are created empty ( size() == 0 )

1
2
3
vector<string> distinct;

vector<int> distinctCount;

To add items to them, you need to increase the size of the vector; for instance with push_back()

OK. I’ve rewritten the code to use «push_back», but I’m still getting «vector subscript out of range» error.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// A program to count the number of times each distinct word is used in an input
#include "chapter3.h"

int main()
{
	// Read the data
	cout << "Enter the words, followed by Ctrl + Z:";
	string x;
	vector<string> words;

		// invariant: words contains all the entered words
	while (cin>>x)
	{
		words.push_back(x);
	}

	// sort the data
	sort(words.begin(),words.end());

	// create vectors for unique words and a count variable
	vector<string> distinct;
	int count = 0;
	vector<int> distinctCount;

	// test for word distinctness and store values in new vectors

	typedef vector<string>::size_type vec_sz;
	vec_sz sizeWords = words.size();
	int i = 0;

	// invariant: there are i distinct words in distinct
	while (i != sizeWords)
	{
		distinct.push_back(words[i]);	
		int temp = 1;
		while (words[i] == distinct[count])
		{
			distinctCount.push_back(temp);
			++temp;
			++i;
		}
		++count;
	}		

	// output the data

	for (int z = 0; z != count; ++z)
	{
		cout << distinct[z] << ": " << distinctCount[z] << endl;
	}
		// hold the execution window open

	cin.clear();
	cin.sync();
	cin.ignore();

	return 0;
}

Am I misusing push_back()? I can already see that using push_back() in my inner while loop is going to cause it to not work the way I would have wanted, but is that what is casing a subscript range error?

Thanks all.

In the following snippet:

1
2
3
4
5
6
		while (words[i] == distinct[count])
		{
			distinctCount.push_back(temp);
			++temp;
			++i;
		}

You increase i but you never insure it doesn’t go past the end of your vector.

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
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
    using namespace std ;

    vector<string> words ;

    cout << "Enter the words, followed by Ctrl + Z:"; // Unix: Ctrl + D 
    string word ;
    while( cin >> word ) words.push_back(word) ;
    // invariant: words contains all the entered words

    // sort the data
	sort(words.begin(),words.end());

    // create vectors for unique words and a count variable
    vector<string> distinct ;
    vector<int> distinctCount ;

    // test for word distinctness and store values in new vectors
    string previous_word = "" ;
    for( vector<string>::size_type i = 0 ; i < words.size() ; ++i )
    {
        if( words[i] != previous_word ) // this is a new distinct word
        {
            distinct.push_back( words[i] ) ; // add it to distinct
            distinctCount.push_back(1) ; // and add a count of 1
            previous_word = words[i] ; // and this now becomes the previous word
        }
        else // not distinct: this is a repetition of the previous word
        {
            distinctCount.back() += 1 ; // just increment the count of the last word
        }
    }

    // output the data
    for( vector<string>::size_type i = 0 ; i < distinct.size() ; ++i )
    {
        cout << distinct[i] << ": " << distinctCount[i] << 'n' ;
    }

    // hold the execution window open
    cin.clear();
    cin.sync();
    cin.ignore();
}

Topic archived. No new replies allowed.

код[1]

При компиляции (1) выдает (2). Что делать? Как бороться?

user avatar

Вы не можете применять оператор индексирования к вектору, который еще не имеет элементов.

Поэтому вам следует написать перед циклами

То есть сначала нужно создать элементы вектора, а затем лишь обращаться к ним по индексу.

Как вариант инициализации (при создании можешь размерность указать):

user avatar

Всё ещё ищете ответ? Посмотрите другие вопросы с метками c++ visual-c++ vector или задайте свой вопрос.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.10.42345

Нажимая «Принять все файлы cookie», вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

ошибка индекса вектора вне допустимого диапазона в c ++

Я пытаюсь написать программу, которая принимает на вход n целых чисел и определяет то, которое встречается на данном входе максимальное количество раз. Я пытаюсь запустить программу для t случаев. Для этого я реализовал алгоритм подсчета, подобный сортировке (возможно, немного наивный), который подсчитывает количество вхождений каждого числа во входных данных. Если есть несколько чисел с одинаковым максимальным количеством случаев, мне нужно вернуть меньшее из них. Для этого я реализовал сортировку.
Проблема, с которой я сталкиваюсь, заключается в том, что каждый раз, когда я запускаю программу на Visual C ++, я получаю сообщение об ошибке «Векторный индекс вне допустимого диапазона». В Netbeans он генерирует возвращаемое значение 1 и завершает работу. Пожалуйста, помогите мне найти проблему

задан 01 фев ’12, 14:02

Это можно решить с помощью отладчика или просто добавив кучу дополнительных cout заявления для проверки всех индексов. — Oliver Charlesworth

@OliCharlesworth: Извините, использование отладчика бесполезно — hytriutucx

@ javacoder990: Да, это так. Просто выполняйте свою программу, пока ее поведение не будет отличаться от ожидаемого. Затем вы нашли свою ошибку. — Oliver Charlesworth

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

Конечно, лучше не красить а переделать, ну да ладно, это же студенческая работа 🙂

И посоветуйте пожалуйста книгу к прочтению, где примерно как Вы объясняют


Интенсив по Python: Работа с API и фреймворками 24-26 ИЮНЯ 2022. Знаете Python, но хотите расширить свои навыки?
Slurm подготовили для вас особенный продукт! Оставить заявку по ссылке — https://slurm.club/3MeqNEk

I’m trying to setup a 2d game and have been thrown up an error on vector subscript out of range. I’ve been trying to look up about it, but have not seen anything that helps. If someone could help and take the time to look at my code and help me fix my error i’d be very grateful. I think it’s got something to do with something about that it can’t handle more then 0-9 or something but my knowledge/understanding of it is not great and would appreciate the help. I’ll paste my code below so you can see what i’m trying to do.

//tile setup
level.loadTexture("gfx/Maptiles.png");
Tile tile;
vector<Tile> tiles;
for (int i = 0; i < 10; i++)
{
    tile.setSize(sf::Vector2f(32, 32));
    tile.setAlive(true);
    tiles.push_back(tile);
}

//sky tile set to false so we don't collide
tiles[0].setAlive(false);
//    X   Y   W   H  of the sprite sheet 
/*tiles[0].setTextureRect(sf::IntRect(187, 51, 70, 70));
tiles[1].setTextureRect(sf::IntRect(0, 0, 70, 70));*/
tiles[0].setTextureRect(sf::IntRect(864, 221, 70, 70));
tiles[1].setTextureRect(sf::IntRect(73, 2, 70, 70));
tiles[2].setTextureRect(sf::IntRect(140, 2, 70, 70));
tiles[3].setTextureRect(sf::IntRect(210, 2, 70, 70));
tiles[4].setTextureRect(sf::IntRect(280, 2, 70, 70));
tiles[5].setTextureRect(sf::IntRect(350, 2, 70, 70));
tiles[6].setTextureRect(sf::IntRect(420, 2, 70, 70));
tiles[7].setTextureRect(sf::IntRect(506, 577, 70, 70)); //ground block
tiles[8].setTextureRect(sf::IntRect(560, 2, 70, 70));
tiles[9].setTextureRect(sf::IntRect(630, 2, 70, 70));
//tiles[].setTextureRect(sf::IntRect(630, 0, 70, 70));
//tiles[11].setTextureRect(sf::IntRect(770, 34, 70, 70));
//tiles[12].setTextureRect(sf::IntRect(840, 51, 70, 70));
//tiles[13].setTextureRect(sf::IntRect(910, 0, 70, 70)); //^^ 1st row
/*tiles[14].setTextureRect(sf::IntRect(0, 0, 70, 70));
tiles[15].setTextureRect(sf::IntRect(70, 0, 70, 70));
tiles[16].setTextureRect(sf::IntRect(140, 0, 70, 70));
tiles[17].setTextureRect(sf::IntRect(17, 34, 70, 70));
tiles[18].setTextureRect(sf::IntRect(34, 34, 70, 70));*/
level.setTileSet(tiles);
// Map dimensions
    sf::Vector2u mapSize(25, 19);
// build map
std::vector<int> map = {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, //25 X 19
    2, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 0, 0, 0,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    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7       
};
//fix tile layout
level.setTileMap(map, mapSize);
level.setPosition(sf::Vector2f(0, 0));
level.buildLevel();


level.render(window);

Понравилась статья? Поделить с друзьями:
  • Ошибка unsatisfied forward or external declaration delphi
  • Ошибка webasto tea
  • Ошибка vdc off nissan teana j32
  • Ошибка unreal engine is exiting due to d3d device being lost error 0x887a0006 hung
  • Ошибка webasto f02 что значит