В массиве размером n допустимый индекс от 0 до n-1
, а не от 1 до n
Предупреждение, когда вы выделяете массив с новым , вы должны освободить его с помощью delete []
Я также рекомендую вам проверить при чтении значения, что чтение успешно, иначе текущий контейнер не установлен и все следующее чтение ничего не сделает
Например, из вашего кода:
#include <iostream>
using namespace std;
int main()
{
int n, x, max;
if ((! (cin >> n)) || (n < 1))
cerr << "invalid size" << endl;
else if ((! (cin >> x)) || (x < 0) || (x >= n))
cerr << "invalid min index" << endl;
else {
int* arr = new int[n];
//Storing the values from the last, since the first element represents
//top of the stack, so the first element would be latest element which
//will be pushed into the stack
for (int i = n-1; i >= 0; i--)
{
if (!(cin >> arr[i])) {
cerr << "invalid value" << endl;
return 0;
}
}
max = arr[n-1];
//Finding the max by iterating from the last position to the no of
//stack operations performed.
for (int i = n-2; i >= x; i--)
{
if (arr[i] > max)
{
max = arr[i];
}
}
cout << max << endl;
delete arr; // must be delete [] arr;
}
return 0;
}
Из-за того, что я проверяю, что было введено целое число, я также проверяю, что размер / мин индексы строго положительны, а также проверяет правильность минимального индекса
Также бесполезно делать цикл, чтобы найти максимум, сравнивающий arr[n-1]
с самим собой, поэтому первый рассматриваемый индекс - n-2
Кажется странным заполнять массив из последнего индекса
Вы используете массив, но вы также можете использовать vector<int>
, std::vector
очень практичны
Компиляция и исполнения:
pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra v.cc
pi@raspberrypi:/tmp $ ./a.out
aze
invalid size
pi@raspberrypi:/tmp $ ./a.out
-1
invalid size
pi@raspberrypi:/tmp $ ./a.out
3 qsd
invalid min index
pi@raspberrypi:/tmp $ ./a.out
3 4
invalid min index
pi@raspberrypi:/tmp $ ./a.out
6 4
1 2 4 3 3 5
2
pi@raspberrypi:/tmp $
Обратите внимание, что результатом является 2, а не 4 из-за сдвига в индексе, если вы хотите, чтобы индекс начинался с 1 для пользователя, выполните
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
if ((! (cin >> n)) || (n < 1))
cerr << "invalid size" << endl;
else if ((! (cin >> x)) || (x < 1) || (x > n))
cerr << "invalid min index" << endl;
else {
x -= 1;
int * arr = new int[n];
//Storing the values from the last, since the first element represents
//top of the stack, so the first element would be latest element which
//will be pushed into the stack
for (int i = n-1; i >= 0; i--)
{
if (!(cin >> arr[i])) {
cerr << "invalid value" << endl;
return 0;
}
}
max = arr[n-1];
//Finding the max by iterating from the last position to the no of
//stack operations performed.
for (int i = n-2; i >= x; i--)
{
if (arr[i] > max)
{
max = arr[i];
}
}
cout << max << endl;
delete arr; // must be delete [] arr;
}
return 0;
}
Компиляция и исполнение:
pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra v.cc
pi@raspberrypi:/tmp $ ./a.out
6 4
1 2 4 3 3 5
4
pi@raspberrypi:/tmp $
Выполнение под valgrind с указанием неверного free arr
:
pi@raspberrypi:/tmp $ valgrind ./a.out
==3761== Memcheck, a memory error detector
==3761== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3761== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3761== Command: ./a.out
==3761==
6 4
1 2 4 3 3 5
4
==3761== Mismatched free() / delete / delete []
==3761== at 0x48491EC: operator delete(void*) (vg_replace_malloc.c:576)
==3761== by 0x10BE7: main (in /tmp/a.out)
==3761== Address 0x4bcb388 is 0 bytes inside a block of size 24 alloc'd
==3761== at 0x48485F0: operator new[](unsigned int) (vg_replace_malloc.c:417)
==3761== by 0x10A9F: main (in /tmp/a.out)
==3761==
==3761==
==3761== HEAP SUMMARY:
==3761== in use at exit: 0 bytes in 0 blocks
==3761== total heap usage: 4 allocs, 4 frees, 22,296 bytes allocated
==3761==
==3761== All heap blocks were freed -- no leaks are possible
==3761==
==3761== For counts of detected and suppressed errors, rerun with: -v
==3761== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $