vector<float> calcProducts()
{
cout << "How many products ? ";
int nProducts;
//Takes imput from user and makes array based on it
cin >> nProducts;
//These are for loop
vector<float> nItemsCount(nProducts);
vector<float> nPrice(nProducts);
int x = 1;
for (int i = 0; i < nItemsCount.size(); i++ & x++)
{
cout <<"How many items of type "<< x << "? ";
cin >> nItemsCount[i];
cout <<"Price of item ? ";
cin >> nPrice[i];
nPrice[i] = nItemsCount[i] * nPrice[i];
}
return nPrice, nItemsCount;
}
//I Have main() in diffrent file main.cpp
int main()
{
vector<float> getValue;
getValue=calcProducts();
}
So i need to return both nPrice and nItemsCount from calcProducts() function for further calculations.
I have tried almost everything but just can't find it anywhere.
This is part of my firs CPP program.
Would appreciate if someone help me with this.
There is no direct way to return 'two values' from a function as you are trying here. There are, however, ways to do so. The two most common are to return a structure of two variables, and the other is to pass at least one array by reference. For example:
vector<float> calcProducts(vector<float>& nItemsCount) {
// ...
// vector<float> nItemsCount(nProducts); - already declared, instead:
nItemsCount.resize(nProducts);
vector<float> nPrice (nProducts);
// ...
return nPrice; // you don't need to return the item count - it is already modified
}
int main() {
vector<float> itemCount;
vector<float> prices = calcProducts(itemCount);
// now both 'itemCount' and 'prices' are set
return 0;
}
Another option would be std::pair:
1 2 3 4 5 6 7 8 9 10 11 12 13
pair<vector<float>, vector<float>> calcProducts() {
// ...
return {nPrice, nItemsCount};
// OR
return make_pair(nPrice, nItemsCount);
}
int main() {
auto ret = calcProducts();
vector<float> prices = ret.first;
vector<float> itemCount = ret.second;
}
Generally, I'd prefer the first one, but sometimes the second one might make more sense.