Novice Coder here: C++ Copying vector into array using functions - c++

Beginner here trying to understand the fundamentals of functions, passing my reference, and vectors/arrays.
My code reads a large data file into a vector. I then, somehow, need to convert the vector into an array, sort the array, and read the output. I believe my issue lies within my attempt to convert the vector to an array.
using namespace std;
//function prototype
int readInput(vector<int> &vect);
void sort(int[], int);
void showArray(int[], int);
int main()
{
vector<int> values;
int sum, avg;
sum = readInput(values);
const int SIZE = values.size(); //ISSUE LIES HERE
int arr[SIZE]; //and here
sort(arr, SIZE);
showArray(arr, SIZE);
avg = sum / values.size();
//cout << "The average is: " << avg;
return 0;
}
int readInput(vector<int> &vect)
{
int count;
int total = 0;
ifstream inputFile("TopicFin.txt"); //open file
if(!inputFile)
{
return 0; // if file is not found, return 0
}
while(inputFile >> count) //read file
vect.push_back(count); //add to file
for (int count = 0; count < vect.size(); count++)
total+=vect[count]; //sum data in vector
return total;
}
void sort(int array[], int size)
{
int startScan, minIndex, minValue;
for(startScan = 0; startScan < (size-1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(int index = startScan + 1; index < size; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
void showArray(const int array[], int size)
{
for(int count = 0; count < size; count++)
cout << array[count] << " " << endl;
}

You don't need to convert the vector to an array. You can sort the vector directly.
std::sort(values.begin(), values.end())
More info on sort here: http://www.cplusplus.com/reference/algorithm/sort/
I will add that in general, you should never use arrays, especially as a new C++ programmer. They are much more complicated than vectors, and are almost never useful in normal C++ code.
http://www.parashift.com/c++-faq/arrays-are-evil.html

Let me preface by saying that, while this is a good thing to do for learning, converting vectors to arrays is probably not something you should do in real code. In reality, you'd use std::sort to sort your vector.
The root of the issue is that you can't declare an array of size that is unknown at compile-time with the int arr[SIZE] syntax.
const int SIZE = values.size();
The value of this is known when the code is executed, but not at compile time. Therefore int arr[SIZE]; cannot work unlike, say, int arr[100]. To declare an array for which you know the size at runtime, you can do it dynamically like
int* arr = new int[size];
and then you are also forced to delete the array manually.

As seanmcl said, you don't need to convert to an array in order to sort. However, if what you want to do is an exercise in writing a sorting function, then you could simply use values.begin() since the elements of vectors are contiguous. (This is not true for other containers.)

Related

If statement is not accessing the value of an array (using the index) when evaluating the expression

I am supposed to be creating a program that asks a user to populate an array of size 10. There are three functions which by their name are self-explanatory; one fills up the array with elements, the second one displays the array horizontally, and the third function checks to see if a number entered by the user is an element in the array.
#include<iostream>
#include<iomanip>
void fillUpArray(int array[], int size);
void displayArray(int array[], int size);
bool isNumberPresent(int array[], int size, int SearchNum);
int main(){
int s = 10; //size of array
int A[s]; //array A with size s
int num; //search number
fillUpArray(A, s);
std::cout <<"\n";
displayArray(A, s);
std::cout << "\n";
std::cout << "Enter a number to check if it is in the array:\n";
std::cin >> num;
std::cout << std::boolalpha << isNumberPresent(A, s, num) << std::endl;
return 0;
}
void fillUpArray(int array[], int size)
{
std::cout << "Enter 10 integers to fill up an array, press enter after every number:\n";
for(int i = 0; i < size; i++){
std::cin >> array[i];
}
}
void displayArray(int array[], int size)
{
for(int j = 0; j < size; j++){
std::cout << array[j] << "\t";
}
}
bool isNumberPresent(int array[], int size, int SearchNum)
{
bool isPresent;
for(int k = 0; k < size; k++){
if(array[k] == SearchNum)
isPresent = true;
else
isPresent = false;
}
return isPresent;
}
That last function, which is a bool function, is not performing the way I thought it would. I thought by doing array[k] whatever index k is then it should spit out the element in the array and then with the expression if(array[k] == SearchNum) it should then work as if(element == SearchNum) but that doesn't seem to be the case and the output is always false.
The for loop in your isNumberPresent function will run to the end of the array (until k equals size) unconditionally; in each run of that loop, you set the value of the isPresent variable according to whether or not the current element is a match for searchNum, overwriting the previous value. So, the function, as it stands, will simply return whether or not the last element in the array is the same as the given test number.
You can simplify that function and remove the need for the local variable: if you find a match, then return true immediately; if the loop ends without finding a match, then return false:
bool isNumberPresent(int array[], int size, int SearchNum)
{
for(int k = 0; k < size; k++){
if(array[k] == SearchNum) return true; // Found a match - we can return immediately
}
return false; // We didn't find a match
}
Note, also, that Variable Length Arrays (VLAs) are not part of Standard C++, though some compilers (like GNU g++) support them (they are part of the C language according to the C99 Standard). In your program, as you only use one (fixed) value for the array size, you can conform to Standard C++ simply by qualifying that s is a const:
int main()
{
const int s = 10; //size of array - make this a "const" be 'proper' C++
int A[s]; //array A with size s
//...

Function and Array in C++: Unexpected output

I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;

How to use the same multidimensional array in many functions?

I'm a beginner at C++ and to be honest, I've got no idea how to solve one task.
I have to create a matrix using a two dimensional array. It's size should be dependent on user's input (it should be like...int matrix[m][n], where m and n are the numbers entered by user). Then I'm supposed to fill it with random numbers from 0 to 100 and print it. Well, I can manage it.
The problem starts when I have to create a function finding the highest number from this array's row. The only parameter of this function can be the number of row entered by user (eg. int function(int i)).
The question is-how can I use the same array in multiple functions? Is there any way to do this, considering the fact that I'm a newbie?
Or maybe the task is formed incorrectly?
Sorry for the long post and thanks in advance
PS Someone asked for code, so here it is:
#include <iostream>
#include <cstdlib>
using namespace std;
int function1(int i)
{
//this is one of the functions I'm supposed to create-I described it earlier
}
int main()
{
int m,n;
cout<<"Matrix's size will be m rows and n columns. Please write m and n"<<endl;
cin>>m>>n;
int A[m][n];
int a,b;
for (a=0;a<m;a++)
{
for (b=0;b<n;b++)
{
A[a][b]=rand()%(100+1);
cout<<A[a][b]<<" ";
}
cout<<"\n";
}
}
EDIT: I'd like to thank you all for help guys. I asked my teacher about that and he finally responded. If you're curious, he told us (I hadn't heard it) to define an array like int[100][100] or higher and not allow user to input any higher numbers ;) That's not an optimal solution but surely a practical one. Thank you again!
The correct way to do this in C++ is to use a std::vector or std::array.
If you cannot do this because of artificial requirements, then there is simply no way you can declare a 2D array in C++ based on user input.
cin >> m >> n;
...
int array [m][n]; // not possible
int** wannabe; // not an array
int array [m * n]; // not possible
What you can do is a "mangled" 2D array:
int* mangled = new int[m * n];
Example of use:
class int_matrix
{
private:
int* mangled;
size_t rows;
size_t cols;
public:
int_matrix(size_t row, size_t col)
:rows(row),
cols(col)
{
mangled = new int[row * col];
}
int highest_in_row (size_t row)
{
...
}
};
Please note that this code requires that you follow the rule of three.
In C you would just have elegantly solved this by writing int array[m][n], but you are using C++ so you can't do that.
You can wrap your function into a class. In that class, you can have your array as member variable.
class A {
int **matrix;
public:
A(int rows, int columns) {
matrix = new int*[rows];
for(int i = 0; i < rows; ++i)
matrix[i] = new int[columns];
}
int function(int i); //you can use your matrix in this function
}
If you can't use classes, you can use global variables.
In a file.cpp
int **matrix;
int function(int i) {
//Do Something
}
//With rows the number of rows and columns the number of columns
//You can take these as parameters
int main() {
matrix = new int*[rows];
for(int i = 0; i < rows; ++i)
matrix[i] = new int[columns];
function(42);
}
If you declare a matrix like int int A[m][n]; where m and n aren't const, you can't pass it to a function. There are two ways to fix it:
1) Declare matrix with const size like int A[10][10];. In this case function which finds max will look like this:
int max_in_row(int matr[10][10], int row) {
int max = 0;
for (int col = 0; col < 10; ++col)
if (matr[row][col] > max)
max = matr[row][col];
return max;
}
and you can find max simple as int max = max_in_row(A, <row you want>);
2) (If you don't know size) Declare matrix as array of arrays:
int **A = new int*[n];
for (int i = 0; i < n; ++i)
A[i] = new int[m];
// fill A like you did
Then the function will look like
int max_in_row(int **matr, int row, int m) {
int max = 0;
for (int col = 0; col < m; ++col)
if (matr[row][col] > max)
max = matr[row][col];
return max;
}
and you can find max by int max = max_in_row(A, <row you want>, m);
The following is not standard C++ because it will only work if the compiler supports Variable Length Arrays. VLA were introduced in C99 and made optional in C11 but were never introduced in C++ standard - but some compilers support it even in C++ mode.
The hack will be to store the matrix address as a global void * and cast it to the proper pointer to VLA inside the function. This hack is required because at the moment of the global declaration you cannot know the number of columns of the matrix.
#include <iostream>
#include <cstdlib>
void *Matrix;
int Columns;
using namespace std;
int function1(int i)
{
typedef int MAT[Columns]; // BEWARE!!! VLA is not standard C++
MAT *mat = static_cast<MAT *>(Matrix);
int mx = mat[i][0];
for(int j=0; j<Columns; j++) {
cout << " " << mat[i][j];
if (mat[i][j] > mx) mx = mat[i][j];
}
std::cout << endl;
return mx;
}
int main()
{
int m,n;
cout<<"Matrix's size will be m rows and n columns. Please write m and n"<<endl;
cin>>m>>n;
int A[m][n]; // BEWARE!!! VLA is not standard C++
int a,b;
for (a=0;a<m;a++)
{
for (b=0;b<n;b++)
{
A[a][b]=rand()%(100+1); // Note that I now use a and b here !
cout<<A[a][b]<<" ";
}
cout<<"\n";
}
Matrix = static_cast<void *>(A);
Columns = n;
cout << "Enter row number to process: ";
cin >> a;
b = function1(a);
cout << "Max of row " << a << " is " << b << endl;
return 0;
}
Not really C++-ish, but at least it compiles and give expected results with clang version 3.4.1

Caling function that uses array as parameter

I'm having some difficulty with my syntax. The purpose of the below program is to print an array of 20 random numbers, find the max of the array and then print the array and the max. I've got the sections to initialize and create the array without any problem, but my issue is with the find_max function. In the main function, I'm trying to work out the syntax to call my find_max function there so I can print the results. If anyone can help to fix my syntax, I'd really appreciate it.
#include <cstdlib>
#include <iostream>
using
namespace std;
void
init_array(int array[], int size, int range)
{
for (int index = 0; index < size; index++)
array[index] = rand() % range;
}
void print_array(int array[], int size)
{
for (int index = 0; index < size; index++)
cout << array[index] << " ";
cout << endl;
}
int find_max (int array[], int size)
{
int max = array[0];
for (int index = 0; index < size; index++)
{
if (array[index] > max)
max = array[index];
}
return max;
}
int main()
{
// Declare array of integers
const int size = 20;
int array[size] = {0};
int max = find_max(array,size);
// Initialize and print array
init_array(array, size, 100);
print_array(array, size);
cout << "The max is:" << max << endl;
return 0 ;
}
Your call of find_max needs to use your declared variables and that after you call init_array. Otherwise your array is empty.
The call to find_max should look like this:
int max = find_max(data, DATA_SIZE);
You try to find max before the array is initialized. That is not what you want. The following works:
const int DATA_SIZE = 20;
int data[DATA_SIZE] = {0};
// Initialize and print array
init_array(data, DATA_SIZE, 100);
print_array(data, DATA_SIZE);
// Find maximum value
int max = find_max(data, DATA_SIZE);
cout << "max = " << max << endl;
return 0;
Well, when declaring the array this way:
int data[DATA_SIZE] = {0};
so all 20 elements in it equals zero.
your main function should look like this:
int main()
{
// Declare array of integers
const int DATA_SIZE = 20;
int data[DATA_SIZE] = {0};
// Initialize and print array
init_array(data, DATA_SIZE, 100);
cout<< find_max(data, DATA_SIZE)<< endl;
print_array(data, DATA_SIZE);
return 0 ;
}
you give the 20 elements random values first by calling init_array and then you try finding the Max of them.
You can give your function the start address of your array and the size of array, then you can use pointers to traverse the array. :)

c++: selectionSort with pointers instead of index

I want to sort numbers using pointers instead of indexes. By the way this is the header file :
int * sort(const int * const array, int size)
And below is the source code I was given
void selectionSort(int list[], int arraySize)
{
for(int i=arraySize-1; i>=1; i--)
{
int currentMax=list[0];
int currentMaxIndex=0;
for(int j=1; j<=i; j++)
{
if(currentMax=list[j])
{
currentMax=list[i];
currentMaxIndex=j;
}
}
if(currentMaxIndex != i)
{
list[currentMaxIndex]=list[i];
list[i]=currentMax;
}
}
}
I know you can switch list[i] to *(list+i) but I don't know how to do it with "currentMaxIndex". I'd really appreciate your help!!
Pointers in C are integers like any others, and can be compared with the usual operations.
So you can do things like:
int *end = list + length; // Create a pointer to one-past the end of an array
for(int *it = list; it < end; it++){ /* use it to read the elements */ }
int *my_favorite_index = list + some_index;
I'm not going to solve your homework for you, but I hope this helps.