C++ C+中的向量初始化+;?

C++ C+中的向量初始化+;?,c++,vector,C++,Vector,我对C++/编码比较陌生,我正在为CS2做最后一个项目。我正在尝试设计一个“配方计算器”,它可以将3种成分输入到一个向量中,然后在配方数据库中搜索潜在的配方 目前,我正在努力解决一些基本问题,当我调用初始化向量的函数时,它不会在主界面中再次输出成分。 当我试图在实际函数中输出向量时,它是有效的。但我想确保相同的向量保存在主目录中的“ingreds”中 int main() { int y; cout << "Hello! Welcome to Abby's Recip

我对C++/编码比较陌生,我正在为CS2做最后一个项目。我正在尝试设计一个“配方计算器”,它可以将3种成分输入到一个向量中,然后在配方数据库中搜索潜在的配方

目前,我正在努力解决一些基本问题,当我调用初始化向量的函数时,它不会在主界面中再次输出成分。 当我试图在实际函数中输出向量时,它是有效的。但我想确保相同的向量保存在主目录中的“ingreds”中

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;
}
intmain()
{
int-y;
不能替换

vector<string> ingredientvector(vector<string> x)
否则,将填充
ingredientvector
内的本地
x
变量,但对
ingredes
没有影响,因为它是通过副本传递的(
x
ingredientvector
内的
ingreds
的本地副本)只有当
ingredientvector
返回
x
然后影响到
ingreds
时,
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;
}
std::vector ingredientvector()
{

std::我真的建议您更好地格式化代码,不要使用命名空间std
。谢谢,我能问一下原因吗?除了使用命名空间std之外,我从来没有被教过做任何事情:使用命名空间std;作者编写
使用命名空间std;
以节省打印成本您的代码返回
“1”
作为一个组成部分。最好将行转换为字符串变量,如果我们通过了测试,则只调用
push_back
。我只是向OP演示如何返回值。逻辑与OPs post中的逻辑相同。
ingreds = 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 << " ";
    }
}