【问题标题】:C++ - Vector will only push_back the last digit of number [closed]C ++ - 向量只会push_back数字的最后一位[关闭]
【发布时间】:2021-04-29 23:01:13
【问题描述】:

当我尝试使用 'a' 选项并选择 12 时,向量只会添加 2:

num_vec's elements: 2 9 2 3 4 6 3 9 4 3 2 3 4 2 3 


=====Menu=====
P - Print Numbers
A - Add a number
M - Display the mean of numbers
S - Display the smallest number
L - Display the largest number
Q - Quit the Program
Enter a choice: a   
Enter number you'd like to add to num_vec: 12

num_vec's elements: 2 9 2 3 4 6 3 9 4 3 2 3 4 2 3 2 

代码:

int main(){
        std::vector<int> num_vec{8,6,4,3,2,7,9,6,2,3,8,3,2,4};
        char choice;

    do{

    std::cout << "\n" << std::endl;
    std::cout << "=====Menu=====" << std::endl;
    std::cout << "P - Print Numbers" << std::endl;
    std::cout << "A - Add a number" << std::endl;
    std::cout << "M - Display the mean of numbers" << std::endl;
    std::cout << "S - Display the smallest number" << std::endl;
    std::cout << "L - Display the largest number" << std::endl;
    std::cout << "Q - Quit the Program" << std::endl;


    std::cout << "Enter a choice: ";
    std::cin >> choice;


    else if (choice == 'A' || choice == 'a'){
            int num;
            std::cout << "Enter number you'd like to add to num_vec: ";
            std::cin >> num;

            num_vec.push_back(num);

     }

感谢任何帮助,对我来说很头疼,但应该很简单。另外,请不要使用没有用的 cmets,例如到目前为止的大多数。 典型的堆栈溢出自我移动。

【问题讨论】:

  • 请张贴Minimal Reproducible Example,您的代码被截断,问题无法重现,而顶部唯一直接相关的是您执行cin &gt;&gt; choice,其中choice 是一个字符,在读取命令之前不会跳过空格,就像你可能想要的那样。
  • change std::cout &lt;&lt; num_vec.at(i) -> std::cout &lt;&lt; i i 是向量中的值而不是索引。
  • auto i:num_vec i 是元素值,而不是元素索引。
  • 漏洞出现在您对std::ignore 的调用中。创建Minimal Reproducible Example 会帮助您找到它。
  • 显然您没有注意到,即使是原始打印输出也与您的原始矢量不一样

标签: c++ arrays vector push-back


【解决方案1】:

您是否注意到您的num_vec 是:

{8, 6, 4, 3, 2, 7, 9, 6, 2, 3, 8, 3, 2, 4}

但它会打印:2 9 2 3 4 6 3 9 4 3 2 3 4 2 3

当你在做的时候发生了什么:

for (auto i : num_vec)
{
    std::cout << num_vec.at(i) << " ";
}

您的i 已经是向量中的数字,而不是索引。如果你扩展你的循环,它基本上是:

std::cout << num_vec.at(num_vec.at(0)) << " ";
std::cout << num_vec.at(num_vec.at(1)) << " ";
std::cout << num_vec.at(num_vec.at(2)) << " ";
  ⋮

或者在你的情况下,它会是:

std::cout << num_vec.at(8) << " ";
std::cout << num_vec.at(6) << " ";
std::cout << num_vec.at(4) << " ";
  ⋮

很幸运,您甚至没有遇到超出范围的异常。相反,它应该是:

for (auto i : num_vec)
{
    std::cout << i << " ";
}

【讨论】:

  • 太完美了!谢谢!尤其是不让我失望。我在评论者与提出问题的人交谈的网站上看到了多个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2016-01-09
  • 2020-07-09
相关资源
最近更新 更多