首页 > 解决方案 > 将可被数字整除的数字插入向量中

问题描述

我得到了整数 15、16、17、18、19 和 20。

我应该只将可被 4 整除的数字放入向量中,然后在向量中显示值。

我知道如何使用数组来解决问题,但我猜我不知道如何正确使用推回或向量。

#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> arrmain; int i,j;

for (int i = 15; i <=20 ; i++)
{
        //checking which numbers are divisible by 4
    if (i%4 == 0)
    {   //if number is divisible by 4 inserting them into arrmain 

        arrmain.push_back(i);
        //output the elements in the vector
        for(j=0; j<=arrmain.size(); j++)
        {
            cout <<arrmain[i]<< " "<<endl;
        }
    }
 }

return 0;
 }

想要的输出:可被 4 整除的数字:16、20

标签: c++vector

解决方案


代码中的主要问题是(1)在打印向量值时使用错误的变量来索引向量,即使用cout <<arrmain[i]而不是cout <<arrmain[j]; (2) 迭代到j <= arrmain.size()( 而不是)时j < arrmain.size()超出arrmain[arrmain.size()]数组边界出界。0..45

一个小问题是您在填充数组时一次又一次地打印数组的内容。您可能希望在第一个循环之后打印一次,而不是在其中一次又一次地打印。

int main()
{
    vector<int> arrmain;

    for (int i = 15; i <=20 ; i++)
    {
        //checking which numbers are divisible by 4
        if (i%4 == 0)
        {   //if number is divisible by 4 inserting them into arrmain

            arrmain.push_back(i);
                    }
    }
    //output the elements in the vector
    for(int j=0; j<arrmain.size(); j++)
    {
        cout <<arrmain[j]<< " "<<endl;
    }

    return 0;
}

关于注释中提到的基于范围的 for 循环,请注意,您可以使用以下缩写语法迭代向量的元素:

// could also be written as range-based for loop:
for(auto val : arrmain) {
    cout << val << " "<<endl;
}

这种语法称为基于范围的 for 循环,例如在 cppreference.com上进行了描述。


推荐阅读