【问题标题】:Can't access my vector variables in different conditions无法在不同条件下访问我的向量变量
【发布时间】:2018-09-24 18:50:28
【问题描述】:

我正在尝试在一种条件下创建对象并在另一种条件下列出这些对象,但它不起作用。

void fillVector(vector<Account>& newcreateAccObj){ 

    string name;
    string password;

    cout<<"Enter your surname:"<<endl;
    cin>>name;
    cout<<"Enter your password:"<<endl;
    cin>>password;

    Account newAcc(name,password);
    newcreateAccObj.push_back(newAcc);
    cout<<endl;     
}

这很好用。

void printVector(vector<Account>& newcreateAccObj){

    unsigned int size=newcreateAccObj.size();

    for(unsigned int i=0;i<size;i++){

        cout<<"Account"<<i+1<<endl;
        cout<<"-----------"<<endl;
        newcreateAccObj[i].getId();
        newcreateAccObj[i].getName();
        cout<<endl;     
    }   
}

当我在相同条件下执行这两个函数时,这也可以正常工作。

但是当我这样做时:

int main(){
int whileCondition=-1;
string girisSecim;

vector<Account>  createAccObj;


while(whileCondition==-1){

    cout<<"--------------------------------------------------------"<<endl;
    cout<<"??????????????????????????????????????????????????????"<<endl;
    cout<<"1-create acc                     2-transferring"<<endl;
    cout<<"3-enter acc                      4-exit"<<endl;
    cout<<"--------------------------------------------------------"<<endl;


    cin>>girisSecim;



        if(girisSecim=="1"){

            fillVector(createAccObj);  //BURDA OBJE OLUSTURULUYOR

        }

        else if(girisSecim=="2"){


        printVector(createAccObj);

        }

        else if(girisSecim=="3"){





        }

        else if(girisSecim=="4"){
            return 0;

        }

        else{
            cout<<"Hatali tuslama."<<endl;
        }


        whileCondition=0;

        cout<<"Programa devam etmek icin -1'i, cikmak icin herhangi bir seyi tuslayiniz."<<endl;

        cin>>whileCondition;
}

编辑:我编辑了主要部分。

我首先选择选项 1。我创建了我的对象并返回了选择菜单,然后我选择了选项 2,它给了我一个空白输出。

【问题讨论】:

  • createAccObj 第二次不是同一个向量,但我们不知道为什么。
  • 为什么不使用循环范围?
  • 我不太清楚@LogicStuff 你能更具体一点吗?
  • 您的帖子中没有与此问题相关的代码 - 请在您调用 fillVectorprintVector 函数的位置添加更多代码上下文(请参阅 minimal reproducible example)。
  • 我添加了完整的主要部分@hnefatl

标签: c++ if-statement pass-by-reference


【解决方案1】:

遵循 createAccObj 的生命周期。

您似乎没有向两个函数发送相同的向量。

我猜一下,你的代码是这样的:

while (input}(
    vector<Account> createAccObj;
    if(input=="1"){
       fillVector(createAccObj);
    }else if(input=="2"){
       printVector(createAccObj);
    }

在这里,在每次迭代中,都会创建新向量,因此当您尝试打印时,会打印空向量。 如果是这种情况,只需移除循环外的矢量减速即可。

编辑: 再次查看代码,好像您在newcreateAccObj[i].getId(); 和newcreateAccObj[i].getName() 中忘记了cout

【讨论】:

  • 我编辑了主要部分。你能再看看吗? @yosim
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多