Here is a simple case where I'm finding the Max of an Array.
Im attempting to use an auto iterator in a array passed into my function.
When I utilize the same code in my function body no error.
The reference inside the function max creates a compile error
cpp:7:14: error: invalid range expression of type 'int *'; no viable 'begin' function available
for (auto& x: array){
^ ~~~~~
Here is my current code, i included a reference to normal usage in "normalMax" and a inline main body function.
I want to know why the iterator in the 'max' function produces an error
#include <iostream>
//max num
//causes an error
int max(int* array){
int max = 0;
for (auto& x: array){
if (x >max)
max = x;
}
return max;
};
//normal behavior
int normalMax(int* array){
int max = 0;
for (int i=0; i<4; i++){
if (i >max)
max = i;
}
return max;
};
int main(){
int A[] = {1,2,3,4,5};
int B[] = {5,6,10,100};
int max = 0;
//Works no Error
for (auto& x: B){
if (x >max)
max = x;
}
std::cout <<max;
//100
normalMax(B);
//max(B);
//compile error
return 0;
}
If you want to pass an array to a function so you the compiler can deduce its length, you'll need to pass it as reference not via a [decayed] pointer:
template <std::size_t N>
int max(int const (&array)[N]) {
int max = 0;
for (auto& x: array) {
if (x >max) {
max = x;
}
}
return max;
}
As a side note: there is no semicolon after the definition of a function. Also, the function isn't particular useful as you should probably rather return the position of the maximum element rather than just its value: the position is determined implicitly anyway and may carry information. Of course, once you locate the correct position you should also return the proper best value which is actually the rightmost version of the maximum.
Related
#include<iostream>
using namespace std;
void MinMax(int tab[],int* min, int& max)
{
int size=0;
for(int i=0; i<4095; i++)
{
if(tab[i]==-1) break;
size++;
}
size=(int)size;
for(int passes=0; passes<size; passes++)
{
if(tab[passes]<tab[passes+1])
{
swap(tab[passes],tab[passes+1]);
};
}
min=tab[size];
cout<<min<<" ";
for(int passes=0; passes<size; passes++)
{
if(tab[passes]>tab[passes+1])
{
swap(tab[passes],tab[passes+1]);
};
}
max=tab[size];
cout<<max<<" ";
}
int main()
{
int z1[]= {10,2,5,7,4,-1};
int min, max;
MinMax(z1,min,max);
for(int i=0; i<7; i++)
{
cout<<z1[i]<<" ";
}
}
I need to write some values in z1 in main function, then execute MinMax. It should find smallest and biggest value from an array. The first problem is when i try to compile it, there is en error about converting int to int* and i can't assign tab[size] to min. I should also use 2 intigers when executing MinMax, but it doesn't work.
void MinMax(int tab[],int* min, int& max)
// ^
This appears to be a typo.
Given the way you're passing the argument, and given the way you're using it inside MinMax, I suspect you meant int&, like you have for max.
The error you are getting is because you assign an integer to a pointer variable by doing min=tab[size]; where min is int * type and tab[size] is int
In order to correct this behavior, you should assign tab[size] to the value min is pointing to with the deference operator: *min = tab[size]
This should correct your error.
I'm currently trying to program a function that would find the average of elements in an array of integers in C++.
I've looked at new c++11 for loop causes: "error: ‘begin’ was not declared in this scope" but I don't quite understand the problem and how to fix it.
double avg(int arr[]) {
double sum = 0;
int size = 0;
for (int i : arr) {
sum += i;
size += 1;
}
return sum / size;
}
It gives me errors that "'begin' was not declared in this scope" and "'end' was not declared in this scope".
Could somebody explain why the error is occurring and possible ways to fix it?
The type int arr[] decays into a raw pointer, and as a result there's no way to get the size of the array it refers to.
Instead of using raw arrays, it'd be better just to use either std::vector:
double avg(std::vector<int> const& v) {
double sum = 0;
for(int i : v)
sum += i;
return sum / v.size();
}
Or std::array, which acts like a C-array but is copyable and doesn't decay into a pointer:
template<size_t N>
double avg(std::array<int, N> const& arr) {
double sum = 0;
for(int i : arr) {
sum += i;
return sum / N;
}
Or, if you really have to use arrays, pass the size as a parameter:
double avg(int arr[], size_t size) {
double sum = 0;
for(int i = 0; i < size; i++) {
sum += arr[i];
}
return sum / size;
}
Leveraging the C++ standard library
The C++ standard library has a lot of useful functions, and one of them, accumulate, does the job perfectly. It takes a begin and end iterator, as well as the initial value, and computes the sum over the range:
#include <numeric>
double avg(std::vector<int> const& v) {
return std::accumulate(v.begin(), v.end(), 0.0) / v.size();
}
double avg(int[] arr, size_t size) {
return std::accumulate(arr + 0, arr + size, 0.0) / size;
}
Functions may not take arrays as parameters. You get a pointer there. Though you can pass a reference to an array to a function as a parameter. Here is an example:
#include <iostream>
template <typename T, auto n>
void print(const T(&arr)[n]) {
for (auto&& t : arr) {
std::cout << t << ' ';
}
std::cout << '\n';
}
int main() {
int arr[]{ 1, 2, 3, 4, 5 };
print(arr);
}
Output:
1 2 3 4 5
If you want to actually pass an array, not switch to using a vector you can do it with a template function parametrized on the size of the array i.e.
template <int N>
double avg(int (&arr)[N] ) {
double sum = 0;
int size = 0;
for (int i : arr) {
sum += i;
size += 1;
}
return sum / size;
}
int main()
{
int ary[] = { 1,2,3,4,5,6 };
std::cout << avg(ary);
}
I have a program where I have a function that sorts elements of an array of structures by their key field. However, when I invoke the function Insertion(a[],7) - I pass the array and its size, the compiler gives an error expected primary expression before ']' token. I would like to ask what am I doing wrong?
#include <iostream>
using namespace std;
struct CElem
{
int key;
};
CElem a[7];
void Insertion(CElem m[],int n)
{
CElem x;
int i;
int j;
for (i = 0; i < n; i++)
{
x = m[i];
j = i-1;
while (j >= 0 && x.key < m[j].key)
m[j+1] = m[j--];
m[j+1] = x;
}
}
int main()
{
a[0].key=32;
a[1].key=45;
a[2].key=128;
a[3].key=4;
a[4].key=-9;
a[5].key=77;
a[6].key=-7;
Insertion(a[],7);
return 0;
}
you only need to pass the pointer to the start of the array:
Insertion(a, 7);
Your parameter m of the method Insertion is of type CElem*. The variable a is of type CElem* too so you are supposed to give the method just a, like Insertion(a,7);.
I am trying to create a program to find the minimum integer in an array of integers. This is my code:
#include<iostream>
using namespace std;
int findMinimum(int array);
int findMinimum(int array){
int arraySize = sizeof(array)/sizeof(int);
int minimum = array[0];
for (int i = 0; i < arraySize; i++){
if (arraySize[i] < minimum){
minimum = arraySize[i];
}
}
return minimum;
}
int main(){
int array[7] = {17,2,10,291,28,10,11};
int minimum = findMinimum(array);
cout << "The minimum of the array is: " << minimum;
}
I am getting this error:
/Users/Danny/Desktop/C++/Practice/arrays.cpp:9:22: error: subscripted value is not an array, pointer, or vector
int minimum = array[0];
~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:11:18: error: subscripted value is not an array, pointer, or vector
if (arraySize[i] < minimum){
~~~~~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:12:26: error: subscripted value is not an array, pointer, or vector
minimum = arraySize[i];
~~~~~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:20:17: error: no matching function for call to 'findMinimum'
int minimum = findMinimum(array);
^~~~~~~~~~~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:7:5: note: candidate function not viable: no known conversion from 'int [7]' to 'int' for 1st argument
int findMinimum(int array){
How do I fix these errors? Thank you.
The function head should be:
int findMinimum(int* array)
However, for an int*, this won't work:
int arraySize = sizeof(array)/sizeof(int);
Therefore you should also pass the size to the function:
int findMinimum(int* array, int size)
You should also consider to use std::vector instead of the array.
This may be cheating:
#include <algorithm>
#include <iostream>
#include <iterator>
int main() {
int array[7] = { 17, 2, 10, 291, 28, 10, 11 };
int min = *std::min_element(std::begin(array), std::end(array));
std::cout << "The minimum of the array is: " << min << '\n';
return 0;
}
What you passed in this line
int minimum = findMinimum(array);
is actually a pointer to an int array... actually, the pointer to the first element. So, you want to change your function signature to
int findMinimum(int* array)
In the modified function int findMinimum(int* array), the line below will be wrong
int arraySize = sizeof(array)/sizeof(int);
because, array is already a decomposed pointer here... so you want to change the function again to
int findMinimum(int* array, int size)
Your complete program will be:
#include<iostream>
using namespace std;
int findMinimum(int* array, int arraySize);
int findMinimum(int* array, int arraySize){
int minimum = array[0];
for (int i = 0; i < arraySize; i++){
if (arraySize[i] < minimum){
minimum = arraySize[i];
}
}
return minimum;
}
int main(){
int array[7] = {17,2,10,291,28,10,11};
int minimum = findMinimum(array, sizeof(array)/sizeof(int));
cout << "The minimum of the array is: " << minimum;
}
I trying to pass an array but don't understand why it gives me those errors. The code is also available in ideone.com
#include <iostream>
using namespace std;
class Max
{
int max = 0;
public:
int getMax(int array[], int size)
{
for(int num : array)
{
if(num > max)
max = num;
}
return max;
}
};
int main( )
{
Max m;
int arr[5] = { 5, 3, 2, 7, 6 };
cout << "Max number is: " << m.getMax(arr,5);
return 0;
}
The problem here as has been mentioned is that passing an array to a function it decays to a pointer. The fix that involves the least changes is to pass the array by reference like so:
template <int U>
int getMax(int (&array)[U])
this fix is probably not the most intuitive for a beginner though. The fix that requires a bit more changes and probably makes more sense to a beginner is to use std::vector or std::array:
int getMax(const std::vector<int> &array)
and in main:
std::vector<int> arr = { 5, 3, 2, 7, 6 };
cout << "Max number is: " << m.getMax(arr);
The cause is the for(:) can not get the size of "int array[]".
You have a size argument, but the begin() & end() can not use it. You must wrap the begin() and end() member functions or just simple it to
for(int i = 0; i< size; i++)
{
int num = array[i];
if(num > max)
max = num;
}
size argument needs type specified (proper type is size_t).
array in getMax function is a pointer (not an array). You can't use range-based for loop with it. You have to use regular for loop which will make use of size argument.