Why wont the vector be empty? - c++

I am wondering why this wont recognize the vector is empty and supply vector pStack with double start? The object of the program is just to simply supply the stack vector with 50 the first time around when it is empty. Then once it is supplied with the starting amount it should subtract with the user input (being bet). Then since its a vector it carries over the old sum into the 2nd time around so it can be subtracted with the user input of bet again.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Bet
{
public:
void set_stack(double n);
void set_bet(double n);
double analyze();
double get_stack();
double get_bet();
private:
double pCount;
double bet;
};
double Bet::analyze()
{
double p = pCount;
double b = bet;
double z = p - b;
return z;
}
void Bet::set_bet(double n)
{
bet = z;
}
double Bet::get_bet()
{
return bet;
}
void Bet::set_stack(double n)
{
pCount = n;
}
double Bet::get_stack()
{
return pCount;
}
double start = 50; // Start needs to go inside of pStack
double bbet;
vector<double> pStack(1);
int main()
{
bool con = true;
while(con){
if(pStack.empty()){
pStack.push_back(start); // pStack should be supplied with start when empty
}
double adjst = pStack[0];
Bet rr;
rr.set_stack(adjst);
pStack.clear();
cout << "Enter min 1 Bet: ";
cin >> bbet;
rr.set_bet(bbet);
double aStack = rr.analyze();
pStack.push_back(aStack);
rr.set_stack(aStack);
double newStack = rr.get_stack();
cout << "Stack: " << newStack << endl;
cout << "Bet: " << bbet << endl;
}
system("pause");
return 0;
}

vector<double> pStack(1);
You are initializing your vector with it having an initial size of 1, that's why your pStack.empty() check returns false.
Do this instead to make its initial state empty.
vector<double> pStack;
Also, remove the empty() check and hoist your push_back outside your while loop.
bool con = true;
pStack.push_back(start);
while(con){
...
You might also want to reconsider your usage of global variables. As far as I can see, you can just put start, bbet and pStack inside main().

You are using the fill constructor. This line will initialize the vector to 1 element, default constructed.
vector<double> pStack(1);
If you wanted the vector to start out empty, you should just use the default constructor.
vector<double> pStack;

When you define the pStack vector you use the constructor that takes an integer that represent the number of elements to allocate.
vector<double> pStack(1);
As a result your vector will have 1 default-initialized element.
To create an empty vector do this:
vector<double> pStack;

Related

How can I print the numbers in main function?

I am new to c++ language. I am trying to solve a problem using function. I have to print the pentagon numbers untill the integer input, but when function returns the values, it only prints one value. I would love some help with it.
#include<iostream>
using namespace std;
int pent(int num){
int p;
for(int i=1;i<=num;i++){
p=(i*(3*i-1)/2);
}
return p;
}
int main(){
int num;
cin>>num;
int sender=pent(num);
cout<<sender<<endl;
return 0;
}
Your function returns int, that is a single integer. To return more, you can use std::vector. As you probably are not familiar with it, I will give you some pointers...
The most simple constructor creates a vector with no entries:
std::vector<int> x;
You can reserve space for elements via reserve:
x.reserve(num);
The vector still has no elements, but it already allocated enough space to hold num elements. This is important, because when we will add elements the vector will grow and that potentially requires to copy all elements to a different place in memory. We can avoid such frequent reallocations by reserving enough space upfront.
To add elements to the vector you can use push_back:
x.push_back(42);
Eventually to print all elements of the vector we can use a range-based for loop:
for (auto element : x) std::cout << element << " ";
So you can rewrite your code like this:
#include <iostream>
#include <vector>
std::vector<int> pent(int num){
std::vector<int> result;
result.reserve(num);
for(int i=1;i<=num;i++){
result.push_back(i*(3*i-1)/2);
}
return result;
}
int main(){
int num;
std::cin >> num;
auto sender = pent(num);
for (auto number : sender) std::cout << number << " ";
}
In your program, from your pent() function you are only returning last calculated value. In you ever time, you are overwriting you variable p.
So there is a way which #asmmo is suggesting, to print in pent() function.
Or you can pass a vector to your pent() function and store values in that and print it in main function.
For your ref:
void pent(int num, vector<int> &arr) {
int p;
for (int i = 1; i <= num; i++) {
arr[i-1] = (i*(3 * i - 1) / 2);
}
}
int main() {
int num;
cin >> num;
vector<int> arr(num);
pent(num, arr);
for (int i = 0; i < num; i++) {
cout << arr[i] << endl;
}
return 0;
}

c++ Variance and Standard Deviation

I have created a program that prompts a user to enter a data set. The program stores and sorts the data, then computes a variance and the standard deviation of the array. However, I am not getting the correct computations for variance and standard deviation (the answer is slightly off). Anyone know what the issue seems to be?
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
//function declarations
void GetData(double vals[], int& valCount);
void Sort(double vals[], int& valCount);
void printSort(double vals[], int& valCount);
double Variance(double vals[], int valCount);
double StandardDev(double vals[], int valCount);
double SqRoot(double value); //use for StandardDev function
//function definitions
int main ()
{
double vals = 0;
int valCount = 0; //number of values to be processed
//ask user how many values
cout << "Enter the number of values (0 - 100) to be processed: ";
cin >> valCount;
//process and store input values
GetData(&vals, valCount);
//sort values
Sort(&vals, valCount);
//print sort
cout << "\nValues in Sorted Order: " << endl;
printSort(&vals, valCount);
//print variance
cout << "\nThe variance for the input value list is: " << Variance(&vals, valCount);
//print standard deviation
cout << "\nThe standard deviation for the input list is: " <<StandardDev(&vals, valCount)<< endl;
return 0;
}
//prompt user to get data
void GetData(double vals[], int& valCount)
{
for(int i = 0; i < valCount; i++)
{
cout << "Enter a value: ";
cin >> vals[i];
}
}
//bubble sort values
void Sort(double vals[], int& valCount)
{
for (int i=(valCount-1); i>0; i--)
for (int j=0; j<i; j++)
if (vals[j] > vals[j+1])
swap (vals[j], vals[j+1]);
}
//print sorted values
void printSort(double vals[], int& valCount)
{
for (int i=0; i < valCount; i++)
cout << vals[i] << "\n";
}
//compute variance
double Variance(double vals[], int valCount)
{
//mean
int sum = 0;
double mean = 0;
for (int i = 0; i < valCount; i++)
sum += vals[i];
mean = sum / valCount;
//variance
double squaredDifference = 0;
for (int i = 0; i < valCount; i++)
squaredDifference += (vals[i] - mean) * (vals[i] - mean);
return squaredDifference / valCount;
}
//compute standard deviation
double StandardDev(double vals[], int valCount)
{
double stDev;
stDev = SqRoot(Variance(vals, valCount));
return stDev;
}
//compute square root
double SqRoot(double value)
{
double n = 0.00001;
double s = value;
while ((s - value / s) > n)
{
s = (s + value / s) / 2;
}
return s;
}
There was quite a bit wrong with the code that was causing your errors. Type mismatches, but more importantly, you never created an array to store the values. You treated a plain double like an array and got lucky your program never crashed on you.
Below is a working version of your code, verified with a made up data set and Excel. I left as much of your code there as possible, just commented out when appropriate. If I commented it out, I didn't make any changes to it, so there may still be errors.
Vector over array in this case. You don't know the size up front (at compile time), and vectors are easier than dynamic arrays. You also never had an array. Vectors also know how big they are, so you don't need to pass the size around.
Type mismatches. Your functions keep expecting an array of doubles, but your sum was an int, among many other mismatches. You were also passing a plain double like it was an array, writing in memory that wasn't yours to change like that.
Best practices to start now. Stop with using namespace std;. Just qualify your names when needed, or be more specific with lines like using std::cout; at the top of a function. Your naming was all over the place. Pick a naming scheme and stick with it. Names starting with a capital letter are generally reserved for classes or types.
#include <iomanip>
#include <iostream>
// #include <array> // You never actually declared a std::array
#include <vector> // You don't know the size ahead of time, vectors are the
// right tool for that job.
// Use what's available
#include <algorithm> // std::sort()
#include <cmath> // std::sqrt()
#include <numeric> // std::accumulate()
// function declarations
// Commented out redundant functions, and changed arguments to match
void get_data(std::vector<double>& vals);
// void Sort(double vals[], int& valCount);
void print(const std::vector<double>& vals);
double variance(const std::vector<double>& vals);
double standard_dev(const std::vector<double>& vals);
// double SqRoot(double value); //use for StandardDev function
// function definitions
int main() {
int valCount = 0; // number of values to be processed
// ask user how many values
std::cout << "Enter the number of values (0 - 100) to be processed: ";
std::cin >> valCount;
std::vector<double> vals(valCount, 0);
// Was just a double, but you pass it around like it's an array. That's
// really bad. Either allocate the array on the heap, or use a vector.
// Moved to after getting the count so I could declare the vector with
// that size up front instead of reserving later; personal preference.
// process and store input values
get_data(vals);
// sort values
// Sort(&vals, valCount);
std::sort(vals.begin(), vals.end(), std::less<double>());
// The third argument can be omitted as it's the default behavior, but
// I prefer being explicit. If compiling with C++17, the <double> can
// also be omitted due to a feature called CTAD
// print sort
std::cout << "\nValues in Sorted Order: " << '\n';
print(vals);
// print variance
std::cout << "\nThe variance for the input value list is: " << variance(vals);
// print standard deviation
std::cout << "\nThe standard deviation for the input list is: "
<< standard_dev(vals) << '\n';
return 0;
}
// prompt user to get data
void get_data(std::vector<double>& vals) {
for (unsigned int i = 0; i < vals.size(); i++) {
std::cout << "Enter a value: ";
std::cin >> vals[i];
}
}
// //bubble sort values
// void Sort(double vals[], int& valCount)
// {
// for (int i=(valCount-1); i>0; i--)
// for (int j=0; j<i; j++)
// if (vals[j] > vals[j+1])
// swap (vals[j], vals[j+1]);
// }
// print sorted values
void print(const std::vector<double>& vals) {
for (auto i : vals) {
std::cout << i << ' ';
}
std::cout << '\n';
}
// compute variance
double variance(const std::vector<double>& vals) {
// was int, but your now vector is of type double
double sum = std::accumulate(vals.begin(), vals.end(), 0);
double mean = sum / static_cast<double>(vals.size());
// variance
double squaredDifference = 0;
for (unsigned int i = 0; i < vals.size(); i++)
squaredDifference += std::pow(vals[i] - mean, 2);
// Might be possible to get this with std::accumulate, but my first go didn't
// work.
return squaredDifference / static_cast<double>(vals.size());
}
// compute standard deviation
double standard_dev(const std::vector<double>& vals) {
return std::sqrt(variance(vals));
}
// //compute square root
// double SqRoot(double value)
// {
// double n = 0.00001;
// double s = value;
// while ((s - value / s) > n)
// {
// s = (s + value / s) / 2;
// }
// return s;
// }
EDIT: I did figure out the variance with an accumulator. It does require knowledge of lambdas (anonymous functions, functors). I compiled to the C++14 standard, which has been the default of major compilers for a while now.
double variance(const std::vector<double>& vals) {
auto meanOp = [valSize = vals.size()](double accumulator, double val) {
return accumulator += (val / static_cast<double>(valSize));
};
double mean = std::accumulate(vals.begin(), vals.end(), 0.0, meanOp);
auto varianceOp = [mean, valSize = vals.size()](double accumulator,
double val) {
return accumulator +=
(std::pow(val - mean, 2) / static_cast<double>(valSize));
};
return std::accumulate(vals.begin(), vals.end(), 0.0, varianceOp);
}
mean = sum / valCount; in Variance will be computed using integer math, then converted to a double. You need to convert to double first:
mean = double(sum) / valCount;
Your SqRoot function calculates an approximate value. You should use std::sqrt instead which will be faster and more accurate.

c++ Problems with operator overloading [duplicate]

This question already has answers here:
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 4 years ago.
My assignment is to use operator overloading to
create a random number array
get lowest number
get highest number
get average
get total and
get standard deviation.
It is just a mess. Here is my code:
#ifndef ASSIGNMENT6_HEAD6_H
#define ASSIGNMENT6_HEAD6_H
#include <iostream>
using namespace std;
class Analyzer {
//Private Member
private:
int numbers;
//Public Member
public:
Analyzer();//default constructor
~Analyzer();//destructor
Analyzer operator+(const Analyzer &a) const;
friend numbers operator+();
};//end of class
#endif //ASSIGNMENT6_HEAD6_H
//Class math with overloading operator and friends
#include "head6.h"
#include <cmath>
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
vector<int> numbers;
int min = numbers[0];
int max = numbers[0];
int sizeofArray;
Analyzer::Analyzer() {
}
int getLowest(const int[], int);
//Random number member
void randNumbers(int sizeofArray, int* numbers[]) {
for (int index = 0; index < sizeofArray; index++)
{
numbers[index] = (numbers() % 499) + 100;
}return;
}
//Setters
int lowest = getLowest(numbers, sizeofArray);
int highest = getHighest(numbers, sizeofArray);
float total = getTotal(numbers);
double average = getAverage(total, sizeofArray);
//Lowest number
void getLowest(const int numbers[], int sizeofArray) {
for (int i = 0; i < sizeofArray; i++) {
if (min > numbers[i]) {
min = numbers[i];
min = lowest;
}
}
return;
}
//Highest number
void getHighest(const int numbers[], int sizeofArray) {
for (int i = 0; i < sizeofArray; i++) {
if (max > numbers[i]) {
max = numbers[i];
max = lowest;
}
}
return;
}
//Total
float getTotal(const int numbers) {
total = sum(numbers[]);
return total;
}
//Average
double getAverage(const float total, int sizeofArray) {
double average = total / sizeofArray;
return average;
}
//standard deviation
float getStandardDeviation(int sizeofArray, float numbers[])const
{
float deviation1;
for (int i = 0; i < sizeofArray; i++)
sum = (mean - numbers[i]) * (mean - numbers[i]);
deviation1 = sqrt(sum / sizeofArray - 1);
float deviation = deviation1;
return deviation;
}
string a() {
stringstream sout;
sout << "STATISTICAL ANALYSIS OF RANDOMLY GENERATED NUMBERS" << endl;
sout << "====================================================" << endl;
sout << left << "Lowest Number:" << left << getLowest() << endl;
sout << left << "Highest Number:" << left << getHighest() << endl;
sout << left << "Numbers Total:" << left << getTotal() << endl;
sout << left << "Numbers Averge:" << left << getAverage() << endl;
sout << left << "Numbers of Standard Deviation:" << left <<
getStandardDeviation() << endl;
return sout.a();
}
int ​​main()
{
Analyzer a;
a + 100;
cout << a;
return 0;
}
Thank you for any assistance.
Your assignment is to use operator overloading to solve the issues - but you actually don't do so anywhere (apart from the operator+ for your Analyzer class – which is meaningless, though).
Reading your lines, I'd rather assume that you're supposed to write separate classes for each task:
class Minimum
{
std::vector<int> const& values
public:
Minimum(std::vector<int> const& values) : values(values) { }
// calculates minimum / lowest value from member:
int operator()();
};
class Maximum
{
public:
//Maximum(); not needed in this variant
// calculates maximum from parameter
int operator()(std::vector<int> const& values);
};
void test()
{
std::vector<int> values({10, 12, 7});
int min = Minimum(values)();
int max = Maximum()(values);
}
These are two different patterns, for consistency, you should select one and implement all classes alike. In first approach, you can access the vector from any member function without having to pass it around as parameter, in second approach, you can re-use one and the same object to calculate the value on several different vectors (you could still maintain a pointer to the vector to avoid passing it around via parameters...).
Coming back to your original code, unfortunately it is full of errors
vector<int> numbers;
int min = numbers[0]; // vector is yet empty! undefined behaviour!
int max = numbers[0];
Actually, you might want not to use globals at all, see later...
//int sizeofArray; // use numbers.size() instead!
// not an error, but questionable: you have a std::vector already, why do you
// fall back to C-style raw arrays?
void randNumbers(int sizeofArray, int* numbers[])
// ^ array of pointers???
{
for (int index = 0; index < sizeofArray; index++)
{
numbers[index] = (numbers() % 499) + 100;
// you certainly intended to use rand function
}
// return; // just plain obsolete
}
// vector variant:
void randNumbers(unsigned int numberOfValues, std::vector<int>& destination)
// ^ not how many numbers ARE in,
// but how many SHALL be inserted
{
// assuming we want to re-use this function and guarantee that EXACTLY
// 'numberOfValues' values are contained:
destination.clear(); // there might have been some values in already...
// assure sufficently internal memory pre-allocated to prevent
// multiple re-allocations during filling the vector:
destination.reserve(numberOfValues);
while(numberOfValues--)
{
numbers.push_back(rand() * 500 / RAND_MAX + 100);
// modulus is unprecise; this calculation will give you better
// distribution
// however, rather prefer modern C++ random number generators!
// IF you use rand: assure that you call srand, too, but exactly ONCE,
// best right when entering main function
}
}
// C++ random number generator:
void randNumbers(unsigned int numberOfValues, std::vector<int>& destination)
{
static std::uniform_int_distribution<> d(100, 599);
static std::mt19937 g;
destination.clear();
destination.reserve(numberOfValues);
while(numberOfValues--)
{
numbers.push_back(d(g));
}
}
Now you have contradicting function declarations:
int getLowest(const int[], int);
void getLowest(const int numbers[], int sizeofArray) { /* ... */ }
int lowest = getLowest(numbers, sizeofArray);
// again: the vector is yet empty!
// so you certainly won't get the result desired
// however, this won't compile at all: numbers is a std::vector,
// but parameter type is array, so you need:
int lowest = getLowest(numbers.data(), numbers.size());
// ^ replaced the redundant global as well
// move this into your main function AFTER having filled the vector!
// picking int as return value:
int getLowest(const int numbers[], unsigned int sizeofArray)
{
// you'd now have to initialize the global first; better, though:
// return a local variable:
// this assumes that there is at least one element in! check before usage
// and decide what would be the appropriate error handling if the vector
// is empty (return 0? return INT_MIN? throw an execption?)
int min = numbers[0];
for (int i = 1; i < sizeofArray; i++)
{
if (min > numbers[i])
{
min = numbers[i];
// min = lowest; // don't overwrite the minimum again!
}
}
// returning at end of void function is obsolete, don't do that explicitly
// well, with int as return value, as is NOW, you NEED to return:
return min;
}
Maximum analogously, be aware that you did not change the comparison from > to <! Be aware that there are already std::min_element, std::max_element and std::minmax_element which do the same (if not prohibited by the assignment, you should rather use these instead of re-inventing the wheel).
// prefere double! float (on typical machines at least) has same size as int
// and it is quite likely that you will lose precision due to rounding; I
// personally would rather use int64_t instead, so you won't run into rounding
// issues even with double and you'd need quite a large amount of summands
// before overflow can occur...
float getTotal(const int numbers) // just one single number???
{
total = sum(numbers[]);
// index operator cannot be applied on a single int; additionally, you need
// to provide an argument; where is 'sum' function defined at all???
return total;
}
// prefer double again
double getStandardDeviation(int sizeofArray, float numbers[]) // const
// (free standing functions cannot be const)
{
// mean isn't declared/defined anywhere (average instead?)!
// and you need to declare and initialize the sum appropriately:
double sum = 0.0;
float deviation1;
for (int i = 0; i < sizeofArray; i++)
sum += (mean - numbers[i]) * (mean - numbers[i]);
// ^ you need to add, if you want to build sum
// why two variables, even both of same type???
deviation1 = sqrt(sum / sizeofArray - 1);
float deviation = deviation1;
return deviation;
// simplest: drop both deviation and deviation 1 and just do:
return sqrt(sum / sizeofArray - 1);
}
Finally: I don't think that you'd use the resulting string (below) for anything else than printing out to console again, so I'd output to std::cout directly (naming the function 'print'); if at all, I'd provide a std::ostream as parameter to be more flexible:
void print(std::ostream& sout)
{
sout << "STATISTICAL ANALYSIS OF RANDOMLY GENERATED NUMBERS" << endl;
sout << "====================================================" << endl;
sout << left << "Lowest Number:" << left << getLowest() << endl;
sout << left << "Highest Number:" << left << getHighest() << endl;
sout << left << "Numbers Total:" << left << getTotal() << endl;
sout << left << "Numbers Averge:" << left << getAverage() << endl;
sout << left << "Numbers of Standard Deviation:" << left
<< getStandardDeviation() << endl;
}
Now you could pass std::cout to, a std::ostringstream object or even write to file via a std::ofstream...
int ​​main()
{
Analyzer a, b, c; // b, c added by me for illustration only
a + 100;
// the operator accepts another Analyzer object, so you could do
c = a + b;
cout << a; // there's no operator<< overload for Analyzer class
// it is HERE where you'd call all your getXZY functions!
return 0;
}
You are passing a pointer to an array of integers:
void randNumbers(int sizeofArray, int* numbers[])
where you really just want to pass numbers as an array. And since all arrays degrade to pointers when passed as a parameter, your function is simply this:
void randNumbers(int sizeofArray, int* numbers) {
for(int index = 0; index < sizeofArray; index++) {
numbers[index]= (rand() % 499) + 100;
};
}
The result is that the items in numbers will be integers in the range of [100..599] inclusive.

C++ beginner declaring a function involving array of structures

There is a few lines of my code that I would like to define as a function because I plan to use it multiple times. portion of code is as follows:
// loop within loop used to reorder with highest price at the top
for(i=0;i<x;i++){
for(t=i;t<x;t++){
if(f[i].price < f[t].price) {
temp = f[i].price;
f[i].price = f[t].price;
f[t].price = temp;
}
}
}
I hope to be able to enter new values for x and f each time I call the function. I have included all of my code below. If I'm unclear about my objective in anyway please feel free to ask. I apologize in advance for the improper terminology I am new to this. Thank you
#include <iostream>
using namespace std;
struct List
{
char name[10];
int price;
};
int main()
{
//x represents number of structures within array!
int x;
cout << "How many items would you like to list under the fruit menu?\n";
cin >> x;
//array of structures fruit
struct List f[x];
int i;
//input values into structure
for (i = 0; i < x; i++) {
cout << "\nEnter fruit name, and price.\n";
cin >> f[i].name;
cin >> f[i].price;
};
//variables for reordering
int temp;
int t;
// loop within loop used to reorder with highest price at the top
for(i=0;i<x;i++){
for(t=i;t<x;t++){
if(f[i].price < f[t].price) {
temp = f[i].price;
f[i].price = f[t].price;
f[t].price = temp;
}
}
}
//Output of menus
//fruit Menu
cout << "\n\nFruit Menu";
for (i = 0; i < x; i++) {
cout << "\n" << f[i].name << " $" << f[i]. price;
};
return 0;
}
I suppose it is an assignment that says "implement your own sort function for sorting an array of fruits", so I take the data structure "array of fruits" as given. You can, of course, change this to vector<struct Fruit> as well, but that's a different topic.
Maybe the following fragments help you finishing your code. It contains functions for entering, sorting, and printing the array with some samples how to deal with the parameters and the calls. You'll have to finalise the code.
Have fun!
#include <iostream>
using namespace std;
struct Fruit
{
char name[10];
int price;
};
// enter up to nrOfFruis; return number of fruits actually entered
int enterFruits(struct Fruit *fruits, int maxNrOfFruits) {
int entered = 0;
while (entered < maxNrOfFruits) {
cin >> fruits[entered].name;
entered++;
}
return entered;
}
void sortFruits(struct Fruit* fruits, int nrOfFruits) {
// your sort code goes here
// example for swaping two elements:
Fruit temp = fruits[0];
fruits[0] = fruits[1];
fruits[1] = temp;
}
void printFruits(struct Fruit *fruits, int nrOfFruits) {
cout << "\n\nFruit Menu";
for (int i = 0; i < nrOfFruits; i++) {
cout << "\n" << fruits[i].name << " $" << fruits[i]. price;
};
}
int main()
{
// Your task: put a proper loop and exit condition arround the following lines...
int x;
cout << "How many items would you like to list under the fruit menu?\n";
cin >> x;
struct Fruit fruits[x];
int entered = enterFruits(fruits, x);
sortFruits(fruits, entered);
printFruits(fruits, entered);
return 0;
}
You cannot allocate an array on the stack if you do not know it's size at compile time. Therefore, you need to dynamically allocate memory for it(you also need to remember to delete it):
//x represents number of structures within array!
int x;
cout << "How many items would you like to list under the fruit menu?\n";
cin >> x;
//array of structures fruit
struct List * f = new List[x];
//...
delete [] f;
Alternatively, you could do it the C++ way, using vector, having the vector elements on the stack:
int x;
std::cin>>x;
std::vector<A> v(x);
for( size_t i = 0; i < x; i++)
{
std::cin >> v[i].x;
}
If you just want to pass an array to a function you can do so like this:
void sortArray(struct List list[]);
void sortArray(struct List* list, int n); // n = size of array
may be better to just use std::vector or some other list container instead. :)
Sounds like you want a function that receives an array t and index x, and you want to mutate the array in the function?
C++ is "pass by value", so to mutate the array you have to have your function take a reference (or pointer) to the array so that you're mutating the original array and not a copy of it, so just have your function signature like this: func(T& t, int x) (assuming T is the type of array t).

Confusion over Initializing variables and changing them in C++

I'm trying to make a program that will allow the user to enter in a heighth and width of a rectangle, and display the area, however every step of my program is done using functions as part of the assignment.
The issue I'm having is that I have the variables assigned and intialized, though I'm not sure how to overwrite them with user inputted data. If I don't initialize the variables at all the program will not run. I was hoping someone could tell me what I'm doing wrong. My code is:
#include <iostream>
using namespace std;
double getWidth(int x);
double getLength(int y);
double getArea(double x, double y, double a);
double displayData(double a);
int main()
{
int x = 0, y = 0, a = 0;
getWidth(x);
getLength(y);
getArea(x, y, a);
displayData(a);
system("pause");
return 0;
}
double getWidth(int x)
{
cout << "Please enter the width: ";
cin >> x;
return x;
}
double getLength(int y)
{
cout << "Please enter the length: ";
cin >> y;
return y;
}
double getArea(double x, double y, double a)
{
a = x*y;
return a;
}
double displayData(double a)
{
cout << a << endl;
return a;
}
There are two ways of passing variables. Method number one is to pass by value. This is the most common method, and it is the one your program is doing. In this method, a copy of the data in the variable is being made and supplied to the function. Your function only changes the copy and not the original variable.
The second method is to pass by reference. When passing by reference, your function effectively has a pointer to the original variable and can thus change it. To pass by reference, put in an ampersand (&) in front of the variable in the function header. Note in the code below that it is not necessary to pass x and y to getArea by reference because getArea only needs to read these variables not write to them.
This however will introduce a new problem for you. When you pass by value it is possible to change the variable type to a larger type without an explicit cast. This is not possible with passing by reference because the different parts of the program would then be trying to treat the variable as a different type. i.e. main wants to write to/read from a as if it is an integer and getArea wants to write to/read from a as if it is a double. These two data types have different sizes and and different formats so this is not possible. Thus you have to declare a is a double in main.
#include <iostream>
using namespace std;
double getWidth(int &x);
double getLength(int &y);
double getArea(double x, double y, double &a);
double displayData(double a);
int main()
{
int x = 0, y = 0;
double a;
getWidth(x);
getLength(y);
getArea(x, y, a);
displayData(a);
system("pause");
return 0;
}
double getWidth(int &x)
{
cout << "Please enter the width: ";
cin >> x;
return x;
}
double getLength(int &y)
{
cout << "Please enter the length: ";
cin >> y;
return y;
}
double getArea(double x, double y, double &a)
{
a = x*y;
return a;
}
double displayData(double a)
{
cout << a << endl;
return a;
}
You seem to be confusing a few different concepts. You should either be passing references and assigning them within the functions, or passing less values and assigning them to some variable in main. For example, your getWidth should be:
double getWidth() {
double w;
cin >> w;
return w;
}
and in your main you should have:
int main() {
/* ... */
double width = getWidth();
/* ... */
}
And so on for the others as well. You should be looking into references and pointers in C++ as well, that would be the other way that you could do this (and you are seemingly confused about). Finally you should definitely find an introduction to functions in some intro to C++ book, as someone said above.