从向量数组循环中获取数据以供以后使用

get data out of vector array loop for later use C++

本文关键字:数据 获取 向量 数组 循环      更新时间:2023-10-16

你好,所以我写了这段代码。它询问你有多少种不同类型的项目,然后基于此创建向量数组。然后问你每种类型有多少件物品,然后问价格,然后计算价格*物品…因此,我需要从循环中取出price * items以供以后使用,下面是我的代码:

float products()
{
    cout << "How many diffrent products ? ";
    int nProducts;
    //Takes number of diffrent type products
    cin >> nProducts;
    //This is for the vector array it takes nProducts as parameter of how many items it has 
    vector<float> fCountPrice(nProducts);
    //This is just for to have diffrent number in each cout
    int x = 1;
    //this loop adds value for all items in array
    for (int i = 0; i < fCountPrice.size(); i++ & x++)
        {
        cout <<"How many of product  "<< x << " you have? ";
        cin >> fCountPrize[i];
        //This asks for price of each product so it can be multiplied
        cout << "Price of product ? ";
        float fPrice;
        cin >> fPrice;
        fCountPrice[i] = fPrice * fCountPrize[i];
        cout << fCountPrize[i] << endl;
        }
}

现在我要弄清楚如何从fCountPrize获取数据以将其返回给程序。这只是这个项目的一小部分。我需要从fCountPrize数组中获取数据,以便在main()函数中使用。我不知道该怎么做。我试图在标题中声明它,但当我试图在主get错误:无效类型'float[int]'为数组下标

#include<iostream>
#include<vector>
using namespace std;
vector<float> products() //change return type
{
        cout << "How many diffrent products ? ";
        int nProducts;
        //Takes number of diffrent type products
        cin >> nProducts;
        //This is for the vector array it takes nProducts as parameter of how many items it has 
        vector<float> fCountPrice(nProducts);
        vector<float> fCountPrize(nProducts);
        //This is just for to have diffrent number in each cout
        int x = 1;
        //this loop adds value for all items in array
        for (int i = 0; i < fCountPrice.size(); i++, x++)
            {
            cout <<"How many of product  "<< x << " you have? ";
            cin >> fCountPrize[i];
            //This asks for price of each product so it can be multiplied
            cout << "Price of product ? ";
            float fPrice;
            cin >> fPrice;
            fCountPrice[i] = fPrice * fCountPrize[i];
            cout << fCountPrize[i] << endl;
            }
            return fCountPrice;
    }
int main(){
   vector<float> retVal;
   retVal=products();
   cout<<retVal[0];

}