简体   繁体   English

C++ 向量 push_back function

[英]C++ vector push_back function

So I am pretty new to coding and am having some issues with storing user input into a vector using the push_back function.所以我对编码很陌生,并且在使用 push_back function 将用户输入存储到向量中时遇到了一些问题。 can some one tell me what I am doing wrong?有人可以告诉我我做错了什么吗?

  vector<int> user_nums;

     switch(selection){
        case 'P':
        case 'p':
            if(user_nums.empty()){
                cout << "[]- list is empty" << endl;
            }else{
                for(auto nums: user_nums)
                    cout <<"[ " << nums << " ]" << endl;
            }
            break;
        case 'A':
        case 'a':
            int new_num;
            cout << "\nEnter a number you would like to add: ";
            cin >> new_num;
             user_nums.push_back(new_num);
            cout << new_num << " was added" << endl;
            break;

This is in a do while loop.这是在 do while 循环中。 The code executes just fine, the problem is when I prompt the user to add a new number the value does not store in the vector.代码执行得很好,问题是当我提示用户添加一个新数字时,该值不会存储在向量中。 So when the user makes the selection to print the numbers, the list still shows empty.因此,当用户选择打印数字时,列表仍然显示为空。

So, you're missing the most relevant sections of your code here.因此,您在这里缺少代码中最相关的部分。 You should really be posting a minimal, reproducible example .你真的应该发布一个最小的、可重现的例子 Often the process of creating one will cause you to find your problem.通常,创建一个的过程会导致您发现问题。

In this case though, it's obvious enough.不过,在这种情况下,这很明显。 There's a loop wrapping all this code.有一个循环包装了所有这些代码。 The vector is declared inside the loop. vector在循环内声明。 That means, at the bottom of the loop the vector will be destroyed, and then as the loop is executed again, a new empty vector will be created.这意味着,在循环的底部, vector将被销毁,然后当再次执行循环时,将创建一个新的空vector

The solution is to move the declaration of the vector outside the loop.解决方案是将vector的声明移到循环之外。

If I've guessed wrong about the structure of the code you haven't shown us, then please follow the guideline I linked to above.如果我对您未向我们展示的代码结构猜错了,请按照我上面链接的指南进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM