簡體   English   中英

C++中的向量初始化?

[英]Vector initialization in C++?

我對 C++/編碼比較陌生,我正在為 CS2 做我的最終項目。 我正在嘗試設計一個“食譜計算器”,它將包含 3 種成分(進入向量),然后在食譜數據庫中搜索潛在的食譜。

目前,我正在努力學習一些基礎知識,當我調用初始化向量的函數時,它不會在 main.js 中再次輸出成分。 當我嘗試在實際函數中輸出向量時,它起作用了。 但我想確保相同的向量保存在主要的“inreds”中。

int main()
{
    int y;
    cout << "Hello! Welcome to Abby's Recipe Calculator." << endl << endl;
    cout << "Please select an option: 1 to search by ingredient or 2 to browse recipes..." << endl;
    cin >> y;

    vector <string> ingreds;
    ingreds.reserve(4); 

    if (y == 1)
    {
        ingredientvector(ingreds);
        for (int i = 0; i < ingreds.size(); i++)
        {
            std::cout << ingreds[i];
        }
    }


    //else if (y == 2)
    //{
    //call recipe function... 
    //}

    system("pause");
    return 0;
}

vector<string> ingredientvector(vector<string> x)
{
    cout << "SEARCH BY INGREDIENT" << endl;
    cout << "Please enter up to three ingredients... " << endl;

    for (int i = 0; i < 4; i++)
    {
        x.push_back("  ");
        getline(cin, x[i]);
        if (x[i] == "1")
        {
            break;
        }
    }

    return x;
}

代替

vector<string> ingredientvector(vector<string> x)

經過

void ingredientvector(vector<string>& x)

並且不要在ingredientvector的末尾返回x 通過引用( & )傳遞,對象可以直接被函數修飾)。


注意:如果您這樣做了,您的代碼可能會起作用:

ingreds = ingredientvector(ingreds);

否則,填充了ingredientvector ingreds局部x變量,但對ingreds沒有影響,因為它是通過復制傳遞的( xingredientvector ingreds的本地副本)。 ingreds如果只受x是由返回ingredientvector然后受災ingreds

但是通過引用傳遞變量絕對是在這里做的正確方法。

返回值時,默認情況下按值返回它們:

std::vector<string> ingredientvector()
{
  std::cout << "SEARCH BY INGREDIENT" << std::endl;
  std::cout << "Please enter up to three ingredients... " << std::endl;
  std::vector<string> x;
  x.reserve(4); 
  for (int i = 0; i < 4; i++)
  {
    x.push_back("  ");
    getline(cin, x[i]);
    if (x[i] == "1")
    {
        break;
    }
  }  
  return x;
}

像這樣使用:

if (y == 1)
{
    const auto ingreds=ingredientvector();
    for (const auto& this_ingred : ingreds)
    {
        std::cout << this_ingred << " ";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM