I am working on a project which requires certain actions be in their own functions. Right now, I must take the random values generated, and output them FROM an array. I have the values stored in numarray , but I don't know how I can call that array in the function to output the values. I have a function set up which seems like it will take the array and output it, but I don't know how to call the function without an argument to pass through it in main. Is this a possible way to output the array, or is there a completely different way this should be done.
PS: I know namespace isn't good, but it's what I have to do to pass the class.
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <cstddef>
using namespace std;
ofstream randomData;
ifstream inputrandomData;
void randomgenerator();
void read();
void printArray(int *numarray);
void randomgenerator() {
srand(time(0));
randomData.open("randomData.txt");
for (int counter = 0; counter < 100; counter++) {
randomData << rand() % 100+1 << endl;
}
randomData.close();
}
void read() {
inputrandomData.open("randomData.txt");
int numarray[100] = {};
for (int i = 0; i < 100; i++) {
inputrandomData >> numarray[i];
}
inputrandomData.close();
}
void printArray(int *numarray) {
for (int index = 0; index < 100; index++) {
cout << numarray[index];
}
}
int main() {
randomgenerator();
read();
printArray();
return 0;
}
The randomgenerator function is what makes the values and stores them in a file.
The read function takes those values and stores them in an array.
printarray is the function where I want to output the array values, and is giving me the problem.
You need to dynamically allocate and return numarray from read. Or even better create numarray like you did here on the stack, but do it in main and pass it as an argument to read, then pass as an argument to printArray.
As it is numarray will go out of scope when read completes, since your allocating it on the stack.
Solution (as per your code): Declare the local array variable in main. Passby pointer to function along with array size as it required to process array inside a passed function. This kind of design is not preferable.
You can design the class as there are some data members involved, on which you can call the method of that class.
You can prefer the std::vector as data member to hold data with a reserve the size as per yours requirement. Because the reserve method of std::vector avoid reallocation as vector size grow. Here, you have size 100. So you can reserve the 100 items of std::vector.
Related
(I'm a student and this is my first time posting so go easy on me.)
I want to create a function that takes a 2D array as an argument and in that array, I'd like to have a variable that I want to modify later in the code. This is the closest thing to an example of what I want:
int size; //the variable I want to change later
void function(int[][size]);
int main(){
cin >> size;
int array[size][size]; //the array I'm using with the variable as a parameter
function(array)
}
void function(int array[][size]){
//Do thing....
}
The code above does give me an error (array bound is not an integer constant) so if I make the variable a constant it will compile as seen here:
const int size = 10;
void function(int[][size]);
int main(){
int array[size][size];
function(array)
}
void function(int array[][size]){
//Do thing....
}
This does compile like I said, but now I can't modify the variable and need to declare its value in the code beforehand. I assume that the variable needs to be global so that I can use it in the function, and with that said, I can't get pointers to work either most likely because it's a global variable and not a local one. Here's an example of something I tried, but got an error (invalid conversion from ‘const int*’ to ‘int*’):
const int size = 10;
void function(int[][size]);
int main(){
int *other = &size;
*other = 5;
}
Any help would be appreciated, thanks.
Plain ol' arrays aren't resizeable in C++. Even more frustrating, their size has to be a constant - you can't make the size a variable that gets set at runtime. Ever more frustrating, the size you put in an array that's a function parameter is a constraint, and it's not even enforced. It's just decor.
As it was hinted in the comments, std::vector<TYPE> is the go-to "resizeable array" in C++. You can create a vector like this:
#include <vector>
int main() {
std::vector<int> my_int_array;
}
And you can resize it like this:
int new_size = 42;
my_int_array.resize(new_size);
And you can pass it to a function by reference(see the &) so that changes to myint_array inside the function affect it outside the function.
void my_awesome_function(std::vector<int>& int_array);
my_awesome_function(my_int_array);
So let's say you have a 2D matrix, implemented as a vector of vectors:
std::vector<std::vector<int>> matrix = { { 1,2,3 }, { 4,5,6 } }
If you want to change the number of columns, you have to resize each row array:
int new_column_count = 10;
for (auto& row : matrix) {
row.resize(new_column_count );
}
You can pass around matrix by reference (e.g. std::vector<std::vector<int>>&) and resize it when you need to.
I have written the following code but it is showing the error
use of parameter outside function body before ‘]’ token
The code is
#include <iostream>
using namespace std;
int n=10;
void a(int s[n][n])
{
cout<<"1";
}
int main()
{
int s[n][n]={0};
a(s);
}
I am trying to pass a multidimensional array of variable size using global variable. I don't want to use vectors in this.
Firstly C++ doesn't have variable-length arrays, So Instead of int s[n][n]={0}; you should use
std::vector<std::vector<int>> s(10,std::vector<int>(10));
Secondly how to pas 2D array to a function,
void a(std::vector<int> **s,int rows, int cols){
cout<<"1";
/* stuff with 2D array */
}
You've already received answers which explain the why. I'm offering this only as a matter of completeness to C++. Personally, though I don't understand why you're avoiding vectors, they do offer a more intuitive or pleasing solution. Inside of your function for handling the vectors, you can always consult std::vector<>.size() to ensure you stay within bounds or std::vector<>.at() and catch the exception that is thrown when accessing out of bounds. Nevertheless, your particular question may also be solved by templates. Below is your code, slightly modified, with comments to illustrate. I tested using gcc 4.8.5:
#include <iostream>
using namespace std;
// Made constant so that the compiler will not complain
// that a non-constant value, at compile time, is being
// used to specify array size.
const int n=10;
// Function template. Please note, however, this template
// will only auto-gen functions for 2D arrays.
template<int lb>
void a(int s[][lb])
{
// output the last element to know we're doing this correctly
// also note that the use of 9 hard-codes this function template
// to 2D arrays where the first dimension is always, at least, 10
// elements long!!!!!!
cout << s[9][lb - 1] << endl;
}
int main()
{
int s[n][1];
s[9][0] = 15;
a<1>(s); // explicitly call template with the size of the last dimension
a(s); // Call the same function generated from the previous call
int t[n][2];
t[9][1] = 17;
a(t); // compiler implicitly determines the type of function to generate
}
You can't. Your function a() needs to know the last dimension, which is the length of each row in the matrix. You need to pass this as an extra parameter to your function.
void a(int * matrix, int rows, int columns) {
int row = ...
int column = ...
if (row < rows && column < columns) {
cout << matrix[row*columns + column];
}
}
int main() {
...
a(&s[0][0], 10);
...
I am a student who is doing an assignment for C++ and I have encountered something I am very unfamiliar with. I have an int array with no size but a list of numbers. After it's creation, there is a function call inside a function that has that array as a parameter with an index in it.
For example:
for (int x = 0; x < CAPACITY, x++)
functionCall(array[x]);
Now I am supposed to create a function so the call can work. However when I make my function:
void functionCall(int array[]);
It does not work because it cannot turn an int to an int[].
I guess my question is, how am I supposed to get that list of numbers created originally by the array if I have to call it in my function as if it isn't an array.
Right now if I just put as an int but not an array like it wants me to do it just gives me the number 5 but not any of the numbers in the array. For example:
void functionCall(int array);
Sincere thank you for anything and I apologize if this sounds confusing.
functionCall(array[x]);
This passes the xth element in the array to the function, so a single int.
array[2] = 5;
functionCall(array[2]); // This is the same as functionCall(5);
So in the function, you get the current element of the array. Not the array itself.
You cannot get the list inside the function, because you only give a single element of that list each time you call it.
Taking a wild guess, I suspect you are looking for something like the MCVE below:
#include <iostream>
void functionCall(int v) {
std::cout << v << " ";
}
void func(int array[], size_t CAPACITY) {
for (size_t x = 0; x < CAPACITY; x++)
functionCall(array[x]);
}
int main() {
int list[] = { 1,2,3,4,3,0, 42 };
func(list, std::distance(std::begin(list), std::end(list)));
return 0;
}
(I'm from C background and new in C++ and its STLs)
I'm writing a C++ array of vectors that will be passed (as a reference of an array of vectors) through a function and will be processed in it.
In this case [in C] I would have passed a pointer to my custom data type (call by value under the hood.)
My code that's giving errors in compile time while trying to do so:
#include <cstdio>
#include <vector>
using namespace std;
/*
the problem is I can't get the syntax. vector<type> &var is
a reference to a single dimension array of vectors.
*/
void pass_arrayOf_vect(vector<int> &array, int lmt);
int main() {
int lmt = 10;
vector<int> lst[lmt];
pass_arrayOf_vect(lst, lmt);
return 0;
}
/*
and the traditional ambiguity of whether using "." or "->" for
accessing or modifying indexes and their members.
*/
void pass_arrayOf_vect(vector<int> &lst, int lmt) {
for (int i = 0; i < lmt; i++) {
lst[i].push_back(i*i);
}
for (int i = 0; i < lmt; i++) {
printf("array[%d]: ", i);
for (int j = 0; j < lst[i].size(); j++) {
printf("%d ",lst[i][j]);
}
printf("\n");
}
printf("\n");
return;
}
In the main function the lst variable is an array of vectors. When you pass this to the pass_arrayOf_vect function you pass a pointer to the first element.
I.e. when you do
pass_arrayOf_vect(lst, lmt);
it's actually the same as doing
pass_arrayOf_vect(&lst[0], lmt);
So the function you call needs to accept a pointer to a vector as its first argument (not a reference):
void pass_arrayOf_vect(vector<int> *array, int lmt);
// ^
// Note use of asterisk instead of ampersand
An even better solution would be to use an std::array of vectors instead. Or if you're on an older compiler without support for std::array, or need the amount to be run-time configurable (in which case you can't use plain C-style arrays anyway), use a vector of vectors.
I'm trying read a large amount of values into a vector in a specific function and then calling it into the main to get the average. My readInput works perfectly. But I believe
my main function returns 0 when I cout << values.size();. Why is this? What can I do to change that?
using namespace std;
//function prototype
int readInput(vector<int> vect);
int main()
{
vector<int> values;
int sum, avg;
sum = readInput(values);
//cout << sum;
avg = sum / values.size();
cout << 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;
}
You are not passing your vector by reference, so your function only stores the values in a copy of your vector from main.
int readInput(vector<int>& vect);
this tells your program to pass the the vector by reference meaning anything modified in the function directly modifies your vector in main. If you're new to this stuff check out this post explaining the difference between reference and copy.
You need to pass the vector as a reference or as a pointer. The function just creates a copy of the vector currently passed by value, and manipulates that.
Change the function signature to . . .
int readInput(vector<int>& vect)
Or (perhaps more weirdly for this example) . ..
int readInput(vector<int> *vect)
also changing the function call to
sum = readInput(&values);
Although others have already mentioned the possibility of passing the vector by reference, that is not what I think I'd do in this case. I think I'd just return the vector from the function. I'd also pass the file name to the function:
std::vector<int> values = readInput("TopicFin.txt");
At least to me, this seems to reflect the intent far better. Maybe I'm just a little slow, but it doesn't seem at all obvious from the name that the return value from readInput would be the sum of the values it read.
While returning a vector could theoretically cause an efficiency problem with a compiler that supported neither move construction nor return value optimization, any such compiler is pretty much guaranteed to be so ancient that you really want to avoid it for other reasons anyway.
As far as reading the data into the vector goes, I'd use a pair of istream_iterators:
std::vector<int> data{std::istream_iterator<int>(infile),
std::istream_iterator<int>()};
Of course, given how simple this is, I'd tend to wonder whether it's worth having a separate function like readInput at all.
To sum the values, I'd use std::accumulate:
int total = std::accumulate(data.begin(), data.end(), 0);