For an assignment for my programming class, I am getting this error:
Error 1 error C2664: 'binarySearch' : cannot convert parameter 1 from 'int' to 'int []' Line 34.
#include<iostream>
using namespace std;
int selectionSort(int[], int);
int binarySearch(int[], int, int);
int sorted;
int main()
{
int size;
int i;
int desirednum;
cout << "How many values do you want to enter?";
cin >> size;
int* userarray = 0;
userarray = new int[size];
for (i = 0; i < size; i++)
{
cout << "Enter a value: ";
cin >> userarray[i];
}
int sorted = selectionSort(userarray, size);//calls the selection sort function
cout << "What value are you looking for: ";//asks what value they are searching for
cin >> desirednum;
int location = binarySearch(sorted, size, desirednum);
delete[] userarray;
return 0;
}
int selectionSort(int numbers[], int size)
{
int i, j, min, minidx, temp, desirednum, sorted = 0;
cout << "What value are you looking for: ";
cin >> desirednum;
for (i = 0; i < (size - 1); i++)
{
min = numbers[i];
minidx = i;
for (j = i + 1; j < size; j++)
{
if (numbers[j] < min)
{
min = numbers[j];
minidx = j;
}
}
if (min < numbers[i])
{
temp = numbers[i];
numbers[i] = min;
numbers[minidx] = temp;
sorted++;
}
}
return sorted;
}
int binarySearch(int& user_array, int amount, int value)
{
int left, right;
int* middle;
left = 0;
right = amount - 1;
while (left <= right)
{
middle = (int*)((left + right) / 2);
if (value == user_array[middle])
{
return *middle;
}
}
}
Your signature (the declaration) is
int binarySearch(int[], int, int);
But your definition is:
int binarySearch(int& user_array, int amount, int value)
This is not the same. The user_array is simply taking an int by reference. You want to take in an array (or a pointer).
As an aside, amount is rather misleading. size would be more accurate and typical.
Here's an example of the expected syntax and usage:
void printArray(int array[], int size) {
for(int i = 0; i < size; ++i) {
std::cout << array[i];
}
}
// Usage
int array[] = {1,2,3};
printArray(array, 3);
Note that the type of the parameter is int[] and not int& (which is merely a reference to an int). You can also use int*.
I haven't looked at C++ in a bit but I can tell in your call to your binarysearch() function, you are passing in a single int and not an integer array. You are passing in the variable "sorted" into binarysearch as the first parameter. "sorted" was declared as int and was assigned the return value of the selectionsort function. selectionsort() is defined with a return type of int.
I think the main problem is you should be passing in the variable "userarray" as the first parameter to binarysearch(). Look at the name if the first parameter to binarysearch().
The value being returned from selectionsort (sorted) appears to only be a counter keeping track of how many swaps had to occur in order to perform the selection sort. If you don't need that info (I don't see any use of that variable) then you could make the selectionsort a void function.
Edit - Also (thanks to Mike), I just noticed the differences in the function declaration vs. definition.
Related
I am new to coding and I am unable to see what is wrong with this Logic.
I am unable to get the desired output for this program.
The Question is to find the minimum and maximum elements of an array.
The idea is to create two functions for minimum and maximum respectively and have a linear search to identify the maximum as well as a minimum number.
#include <iostream>
#include<climits>
using namespace std;
void maxElement(int a[], int b)
{
// int temp;
int maxNum = INT_MIN;
for (int i = 0; i < b; i++)
{
if (a[i] > a[i + 1])
{
maxNum = max(maxNum, a[i]);
}
else
{
maxNum = max(maxNum, a[i+1]);
}
// maxNum = max(maxNum, temp);
}
// return maxNum;
cout<<maxNum<<endl;
}
void minElement(int c[], int d)
{
// int temp;
int minNum = INT_MAX;
for (int i = 0; i < d; i++)
{
if (c[i] > c[i + 1])
{
minNum = min(minNum,c[i+1]);
}
else
{
minNum = min(minNum,c[i]);
}
// minNum = min(minNum, temp);
}
// return minNum;
cout<<minNum<<endl;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
minElement(arr,n);
maxElement(arr,n);
return 0;
}
You are already comparing each element to the current max / min. It is not clear why in addition you compare to adjacent elements. Trying to access a[i+1] in the last iteration goes out of bounds of the array and causes undefined behavior. Just remove that part:
void maxElement(int a[], int b)
{
// int temp;
int maxNum = INT_MIN;
for (int i = 0; i < b; i++)
{
maxNum = max(maxNum, a[i]);
}
cout<<maxNum<<endl;
}
Similar for the other method.
Note that
int n;
cin >> n;
int arr[n];
is not standard C++. Variable length arrays are supported by some compilers as an extension, but you don't need them. You should be using std::vector, and if you want to use c-arrays for practice, dynamically allocate the array:
int n;
cin >> n;
int* arr = new int[n];
Also consider to take a look at std::minmax_element, which is the standard algorithm to be used when you want to find the min and max element of a container.
Last but not least you should seperate computation from output on the screen. Considering all this, your code could look like this:
#include <iostream>
#include <algorithm>
std::pair<int,int> minmaxElement(const std::vector<int>& v) {
auto iterators = std::minmax_element(v.begin(),v.end());
return {*iterators.first,*iterators.second};
}
int main()
{
int n;
std::cin >> n;
std::vector<int> input(n);
for (int i = 0; i < n; i++)
{
std::cin >> input[i];
}
auto minmax = minmaxElement(input);
std::cout << minmax.first << " " << minmax.second;
}
The method merely wraps the standard algorithm. It isnt really needed, but I tried to keep some of your codes structure. std::minmax_element returns a std::pair of iterators that need to be dereferenced to get the elements. The method assumes that input has at least one element, otherwise dereferencing the iterators is invalid.
okay I literally have no idea what this error means. The * is for pointers right? I'm not using pointers so I don't understand what is happening? This is for my second programming class so I am quite new still. Any help would be much appreciated!!
MAIN.CPP
#include <iostream>
#include "arr.hpp"
int main()
{
int size = getInteger();
int array;
fillArray(array,size);
sortArray(array, size); //THE ERROR COMES UP FOR ALL OF THESE FUNCTIONS.
displayArray(array, size);
binSearch(array, size, value);
return 0;
}
ARR.CPP
#include "arr.hpp"
#include <iostream>
int getInteger()
{
int value;
std::cout << "Please enter integer between 10 and 20 for size of array: ";
std::cin >> value;
// check if size is in range
if (value >= 10 && value <= 20)
{
return value;
}
else
{
std::cout << "Error. Please enter a correct value." << std::endl << std::endl;
std::cin.clear(); //clears error from cin.fail()
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //removes old cin input for value
std::cin >> value;
}
return value;
}
void fillArray(int array[], int size)
{
std::srand(static_cast<unsigned>(std::time(0)));
for (int i = 0; i < size; i++)
{
array[i] = (std::rand() % 99)+1;
}
}
void sortArray(int array[], int size)
{
std::sort(array, array+size);
}
void displayArray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
std::cout << array[i] << std::endl;
if((i+1)%5 == 0)
{
std::cout << std::endl;
}
}
}
bool binSearch(int array[], int size, int value)
{
int low = 0;
int high = size - 1;
int mid;
while(low <= high)
{
mid = (low+high) / 2;
if(value == array[mid])
{
return mid;
}
else if (value > array[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
ARR.HPP
#ifndef arr_hpp
#define arr_hpp
int getInteger();
void fillArray(int array[], int size);
void sortArray(int array[], int size);
void displayArray(int array[], int size);
bool binSearch(int array[], int size, int value);
#endif /* arr_hpp */
You are declaring array as an integer, instead of an array. I presume you want to declare an array of size size and pass it to the function.
You're missing the declaration of value.
To fix it, replace the declaration of array and declare value:
int size = getInteger();
int array[size];
int value;
...
Edit:
As mentioned in the comments, the above suggestion is not legal in standard C++. For your program to compile with legal C++, you might have a couple of choices:
Make size known at compile-time, e.g. 100, and ask the user to input a number between 0 and 100.
Use a data structure, like an std::vector and modify all function definitions accordingly.
This question already has answers here:
Why is my HelloWorld function not declared in this scope?
(11 answers)
Closed 5 years ago.
I'm trying to write a program that displays asterisks and spaces based on their input and I've run into a compiler problem:
chart.cpp:24:41: error: ‘find_largest’ was not declared in this scope
int largest = find_largest(values, size);
This is my code:
/*
* Project 1
* Author: Erik Ingvoldsen
* Date: 2/1/2018
*/
#include <iostream>
using namespace std;
int size = 0; //initalizing "size" at 0.
const int MAX = 100; //setting max value
int values[MAX]; //100 int limit
int main(){
int num;
for (int i = 0; i < MAX; i++) {
cin >> num; //allow the user to put in a number
values[i] = num; //assigning value to the array
if (num <= 0) {
break; //stop if "0" or lower is entered
}
size++; //increase the size of array, assuming the for loop hasn't been broken
}
int largest = find_largest(values, size); //setting the amount of rows
for (int i = 0; i < size; i++) {
if (values[i] = largest) {
cout << "*"; //if the value of the area reachest the highest row, give a *
} else {
cout << "\n"; //otherwise just give a blank space
}
largest--; //by shrinking "largest", we move down the next row
cout << endl;
}
return 0;
}
int find_largest(int values[], int size) {
int largest = 0;
for (int i = 0; i < size; i++) {
if (values[i] > largest) {
largest = values[i]; //if the value of the array is bigger than the current largest it is replace
}
}
return largest; //once the for loop is completed, it returns the largest number found
}
I really can't tell the difference between this and the function...and I'm pretty sure I'm not supposed to declare it as "int largest = find_largest(values[], size);"
You are supposed to declare all functions before you use them. Simple way to do that is to use a prototype.
// prototype
int find_largest(int values[], int size);
int main(){
...
}
int find_largest(int values[], int size) {
...
}
I am writing a program to generate and sort an array of random numbers.
The compiler gives me the following error:
select.cxx: In function ‘void selectionsort(Item*, SizeType)
[withItem = int, SizeType = long unsigned int]’:
select.cxx:95: instantiated from here
select.cxx:16: error: no matching function for call to ‘swap(int*&, long unsigned int&, long unsigned int&)’
Here is my code:
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
template <class Item, class SizeType>
void selectionsort(Item data[], SizeType n)
{
for (SizeType i = 0; i = n - 2; i++)
{
SizeType j = index_of_minimal(data, i, n);
swap(data, i, j); //data[i] swapped with data[j](minimum)
}
}
template <class Item, class SizeType>
std::size_t index_of_minimal(const Item data[], SizeType i, SizeType n)
{
size_t min = i; //holds index of minimum (initialized to i)
Item t1 = data[i]; //temporary holder for comparing values, initialized as i (starting value)
Item t2; //second holder
for (SizeType j = i++; j = n - 1; j++)
{
t2 = data[j];
if (t2 < t1)
{
t1 = data[j];
min = j;
}
}
return min;
}
template <class Item, class SizeType>
void swap(Item data[], SizeType i, SizeType j) //data[i] swapped with data[j](minimum)
{
Item temp; //holds value to be swapped
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
template <class Item, class SizeType>
void listPrint(Item data[ ], SizeType n)
{
cout << "array:";
for (SizeType i = 0; i = n - 1; i++)
{
cout << " " << data[i];
}
cout << endl;
}
int myrand(int lower, int upper)
{
return (lower + rand() % ( upper - lower + 1 ) );
}
int main()
{
size_t n; //user input
//For random number generator//
srand(time(NULL));
cout << "Please enter a number:" << endl;
cin >> n;
while (n < 1)
{
cout << "Error: please enter a number 1 or larger" << endl;
cin >> n;
}
int rNumbers[n]; //declares int array of size n
int randomN; //to hold randomly generated number
for (size_t i = 0; i < n; i++)
{
randomN = myrand(1, 1000); //generates a random number as randomN
rNumbers[i] = randomN;
}
cout << "Unsorted ";
listPrint(rNumbers, n);
selectionsort(rNumbers, n);
cout << "Sorted ";
listPrint(rNumbers, n);
}
I have a feeling that the problem has to do with the data types passed to the swap function. I am also confused as to why the first line of the error states that SizeType = long unsigned int, when the data type of n as declared in main() is size_t.
Make sure that the other functions you call inside your template function are visible. So, define selection_sort() after swap() and index_of_minimal().
Side remark:
int rNumbers[n]; //declares int array of size n
declares a variable sized array, which is not standard C++ (some compilers support it though, but you shouldn't rely on this). If you want a run-time sized array, use std::vector instead.
Regarding your confusion at the end, size_t is a type alias, which in your implementation it happens to be for unsigned long int, so that's why the error mentions it.
My complete program is as follows:
#include<iostream>
using namespace std;
int max(int *,int);
int main()
{
int n, a[10], b;
cout << "Please enter the no. of integers you wish to enter ";
cin >> n;
for(int i = 0; i < n; i++)
{
cout << endl << "please enter the " << i+1 << " no. ";
cin>>a[i];
}
b = max(&a[0], n);
cout << endl << "The greates no. is " << a[b] << " and its index position is " << b;
return 0;
}
int max(int * ptr,int n)
{
int b[10], i, max, k;
&b[0] = ptr;
max = b[0];
for(i = 0; i < n; i++)
{
if (max < b[i]);
max = b[i];
k = i;
}
return k;
}
I want to pass pointer to the function and find the greatest number.
I'm not sure if passing an array counts as passing pointers.
You don't need to allocate memory for b[10], you just need a pointer here, instead of
int b[10];
Just declare a pointer and set its address to the starting element of the array passed by the function.
ie
int* b= ptr;
#include<iostream>
using namespace std;
int max(int *,int);
int main()
{
int n,a[10],b;
cout<<"Please enter the no. of integers you wish to enter ";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<endl<<"please enter the "<<i+1<<" no. ";
cin>>a[i];
}
b=max(a,n);
cout<<endl<<"The greates no. is "<<a[b]<<" and its index position is "<<b;
return 0;
}
int max(int *a,int n)
{
int i,max,k=0;
//&b[0]=ptr;
max=a[0];
for(i=1;i<n;i++)
{
if(max<a[i])
max=a[i];
k=i;
}
return k;
}
Try this program .
It does not use b[] , which is actually unnecessary , just pass array a as parameter .
CHANGES :
b=max(a,n);
int max(int *a,int n)
{
int i,max,k=0; // INITIALIZE k !
//&b[0]=ptr;
max=a[0];
for(i=1;i<n;i++)
{
if(max<a[i])
max=a[i];
k=i;
}
return k;
}
You should initialize K to 0 .
Your function is invalid You may not make assignment
&b[0] = ptr;
an such an assignment has no sense because it tries to change the address of array element b[0].
You need not to declare any additional array in the function.
Moreover your function has undefined beahviour in case then the first element is the maximum element of the array. In this case the function returns variable k that was not initialized.
Also after the if statement there is a semicolon
if (max < b[i]);
So this statement also has no sense.
The function can be written simpler
int max( const int * ptr, int n )
{
int max_i = 0;
for ( int i = 1; i < n; i++ )
{
if ( ptr[max_i] < ptr[i] ) max_i = i;
}
return max_i;
}
change your expression to :
b=max(a,n);
You need not pass array via reference, they are automatically passed by reference.
also change:
&b[0]=ptr; to b=ptr;
but for that initialize b as int * b;
or simply,
don't assign value of ptr to b, just directly work on ptr.