Ошибка "Vector subscriptout of range''

260
22 января 2018, 08:25

Начал недавно учиться программировать на c++ при выборе функции enter() во второй раз, моя программа выдаёт ошибку vector subscript out of range

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <clocale>
void menu();
void enter();
void hide();
void size();
using namespace std;
struct ty
{
    string name;
    string region;
    long population;
    string stat;
};

vector<ty> sities(1);

int main()
{
    string mestr;
    while (mestr != "q" || mestr != "Q")
    {
        menu();
        cout << "Command: _\b";
        cin >> mestr;
        if (mestr == "e" || mestr == "E")
            enter();
        else if (mestr == "h" || mestr == "H")
            hide();
        else if (mestr == "s" || mestr == "S")
            size();
    }
    return 0;
}
void menu()
{
    cout << "Enter:\n   <q to exit>    <e to enter the city>   <h to hide>\n";
    cout << "   <s to show size>\n";
}
void enter()
{
    int * te = new int;
    *te = 0;
    sities.push_back(sities[*te]);
    while (sities[*te].name != "\0")
    {
        *te++;
    }
    cout << "Enter the name:\n";
    cin >> sities[*te].name;
    cout << "Enter the region:\n";
    cin >> sities[*te].region;
    cout << "Enter the population:\n";
    cin >> sities[*te].population;
    cout << "Enter tne stat:\n";
    cin >> sities[*te].stat;
    sities[*te + 1].name = "\0";
    sities[*te + 1].region = "\0";
    sities[*te + 1].population = 0;
    sities[*te + 1].stat = "\0";
    delete te;
}
void hide()
{
    cout << "Enter: ";
    string * nm = new string;
    int * th = new int;
    *th = 0;
    cin >> *nm;
    while (sities[*th].name != *nm)
    {
        *th++;
    }
    cout << "Informatiom:\n";
    cout << "  Region: " << sities[*th].region;
    cout << "  Population: " << sities[*th].population;
    cout << "  Stat: " << sities[*th].stat << endl;;
    delete nm;
    delete th;
}
void size()
{
    int * s = new int;
    *s = size(sities) - 1;
    cout << *s << " elements" << endl;
    delete s;
}

Всё перепробовал. Если есть ещё замечания по работе программы - пишите. #include "stdafx.h" обеспечивает доступ к заголовочному файлу.

Answer 1

Ну, как минимум, вы не пробовали вместо

while (sities[*te].name != "\0")
{
    *te++;
}

написать

while (sities[*te].name != "\0")
{
    (*te)++;
}

Вы меняете указатель, а не значение, на которое он указывает...

while (sities[*th].name != *nm)
{
    *th++;
}

Тут вы сами исправите? :)

Но объясните вообще, "какой черт занес вас на эти галеры?" (с) - зачем вам это нужно - динамические выделение одного int?

Кстати, как и непонятно какой первый элемент в sities:

vector<ty> sities(1);

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

P.S. Только оно все равно не будет нормально работать - например, при поиске в hide несуществующего имени...

P.P.S. Конечно, это не мое дело, но называть hide функцию поиска, а массив городов - sities - как-то не комильфо.

Answer 2

#include "stdafx.h" 
#include <iostream> 
#include <string> 
#include <vector> 
 
 
void menu(); 
void enter(); 
void hide(); 
void size(); 
 
using namespace std; 
 
struct ty 
{ 
	string name; 
	string region; 
	string regiontype; 
	long population; 
	string stat; 
}; 
 
 
vector<ty> sities; 
 
ty buffer; 
 
 
 
int main() 
{ 
	string mestr; 
	menu(); 
	cout << "Command: _\b"; 
	cin >> mestr; 
	while (mestr != "4") 
	{ 
		if (mestr == "1") 
			enter(); 
		else if (mestr == "2") 
			hide(); 
		else if (mestr == "3") 
			size(); 
		else if (mestr != "1" || mestr != "2" || mestr != "3" || mestr != "4")  
			cout << "\nUnknown command" << endl; 
		menu(); 
		cout << "Command: _\b"; 
		cin >> mestr; 
    } 
	 
	return 0; 
} 
void menu() 
{ 
	cout << "Enter:\n   <1 to enter the city>   <2 to hide>\n"; 
	cout << "   <3 to show size>   <4 to exit>\n"; 
} 
void enter() 
{ 
	sities.push_back(buffer); 
	int * te = new int; 
	*te = size(sities) - 1; 
	cout << "Enter the name: "; 
	cin >> sities[*te].name; 
	cout << "Enter the region: "; 
	cin >> sities[*te].region >> sities[*te].regiontype; 
	cout << "Enter the population: "; 
	cin >> sities[*te].population; 
	cout << "Enter the status: "; 
	cin >> sities[*te].stat; 
	delete te; 
} 
void hide() 
{ 
	cout << "Enter: "; 
	string * nm = new string; 
	int * th = new int; 
	int * th1 = new int; 
	*th1 = size(sities); 
	cin >> *nm; 
	for (*th = 0; (*th) < (*th1); ++(*th)) { 
		if (sities[*th].name == *nm) 
		{ 
			cout << sities[*th].region << " " << sities[*th].regiontype << 
				"\nPopulation: " << sities[*th].population << "   Status: " << sities[*th].stat << endl; 
			delete th; 
		} 
		else if (*th == *th1)  
		{ 
			cout << "Not found\n"; 
			delete th; 
		} 
	} 
	 
	delete nm, th1; 
} 
void size() 
{ 
	int * s = new int; 
	*s = size(sities); 
	cout << *s << " elements" << endl; 
	delete s; 
}

READ ALSO
Не удаётся скомпилировать код с файлом в качестве аргумента main (file.open(argv[1]))

Не удаётся скомпилировать код с файлом в качестве аргумента main (file.open(argv[1]))

В среде MVS2015 следующий код и вообще любой подобный:

246
с++ округляет деление

с++ округляет деление

Не могу понять причину, почему при делении вещественных чисел результат сам по себе округляется до 5 знаков после запятой

228
Работа с QDateEdit и QTimeEdit c++

Работа с QDateEdit и QTimeEdit c++

Как передать дату из QCalendarWidget в QDateEdit который находится на отдельном окне

252
OpenGL и C++ на Linux

OpenGL и C++ на Linux

Учу OpenGL на C++Сам работаю на Linux Mint

217