Когда вы делаете vect.push_back(make_pair(name[i], score[i]));
, он создает новые объекты в массиве, нет ссылок на std::string name[MAX];
и int score[MAX];
. Поэтому, когда вы вводите std::cin >> name[i] >> score[i];
, вы изменяете массив name
и массив score
, ваш вектор (vect
) остается неинициализированным.
Вам нужно создать временные std::pair < std::string, int> pair_input;
и push_back для проверки каждой итерации, например:
// gets input for names and test scores
for (int i = 0; i < n; i++)
{
std::pair < std::string, int> pair_input;
std::cin >> pair_input.first >> pair_input.second;
vect.push_back(pair_input);
}
Удалить часть отталкивания, где вы инициализировали свой вектор раньше:
// //pairs arrays
// for (int i = 0; i < MAX; i++)
// {
// vect.push_back(make_pair(name[i], score[i]));
// }
потому что мы будем делать push_back для вектора каждой операции ввода. После всех изменений ваш код выглядит так:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
const int MAX = 300;
int n;
int y;
int x; // find what the difference between the highest score and 100
std::vector<std::pair < std::string, int>> vect;
//Asks for # of tests for loop
std::cout << "Hello, How many tests do you need to grade?" << std::endl;
std::cin >> n;
std::cout << "Please enter a grade then press enter. Repeat until you havereached the number specified in the previous step" << std::endl;
std::cout << "DO NOT ENTER DECIMALS" << std::endl;
// gets input for names and test scores
for (int i = 0; i < n; i++)
{
std::pair < std::string, int> pair_input;
std::cin >> pair_input.first >> pair_input.second;
vect.push_back(pair_input);
}
// sorts tests
std::sort(vect.begin(), vect.end());
//add a space for easier reading
std::cout << " " << std::endl;
//finds the difference between the highest scores and 0
x = 100 - vect[0].second;
for (int i = 0; i < n; i++)
{
std::cout << vect[i].first << vect[i].second + x << std::endl;
}
std::cout << "enter a value then press enter to close";
std::cin >> y;
return 0;
}
Пока я тестировал, я получил следующий результат:
Hello, How many tests do you need to grade?
2
Please enter a grade then press enter. Repeat until you havereached the number specified in the previous step
DO NOT ENTER DECIMALS
test
2
test3
3
test100
test3101
enter a value then press enter to close