What are you learning here? Memory management or logic of finding a value from array?
If the latter, then let vector manage the memory (for now).
(You should learn the use of standard containers anyway.)
Remember that input can fail. (Never trust the user.)
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
|
#include <iostream>
#include <vector>
int main ()
{
int n = 0;
std::cout << "How many numbers would you like to type? ";
std::cin >> n;
if ( n < 4 || 1024 < n ) {
std::cout << "Invalid input!\n";
return 1;
}
std::vector<int> p;
p.reserve( n ); // preallocate memory without creating elements
int value = 0;
int i=0;
while ( i < n && std::cin >> value )
{
// add value only if read was successful
p.emplace_back( value );
}
// p has at most n values
// show p
for ( int v : p ) {
std::cout << v << ' ';
}
std::cout << '\n';
}
|
This is how standard library would solve the half largest:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <vector>
#include <algorithm>
int main ()
{
// input
std::vector<int> p {52, 91, 2, 7, 78, 10};
// find largest element
auto m = std::max_element( p.begin(), p.end() );
// modify
*m /= 2;
// show p
for ( int v : p ) {
std::cout << v << ' ';
}
std::cout << '\n';
}
|
The key thing to notice is that the std::max_element does not return a value. It returns the position (in range) of the largest value (just like
againtry's loop does).
You could merge the input loop and the find largest element loop, if you write both by hand.
@againtry:
i < size - 1
? Why do you skip the last element?
Ganado's "by value" approach changes {8,2,3,8} into {4,2,3,4}.
The "find largest" returns {4,2,3,8}.
Choose the approach that does what you want.