将可被数字整除的数字插入到向量中

Insert numbers divisible by a number into a vector

本文关键字:数字 插入 向量      更新时间:2023-10-16

我得到了整数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

正如注释中已经提到的,您的代码中存在一些问题。 在编写更多代码时,所有这些都会最终咬你。 其中很多都可以通过编译器工具告诉您。例如,在叮当声中使用-Weverything

要挑选最重要的:

源.cpp:8:10: 警告:声明会隐藏局部变量 [-Wshadow]

for (int i = 15; i <=20 ; i++)

来源.cpp:6:26: 警告:未使用的变量"i" [-Wunused-变量]

矢量阿尔曼; 国际 i,j;

除此之外,您的代码中还有一个逻辑问题:

for values to check
if value is ok
print all known correct values

这将导致:运行时为 16、16、20。 相反,您希望更改打印范围,以便它不会在每个匹配项上打印。

最后,您看到的错误:

for(j=0; j<=arrmain.size(); j++)
{
cout <<arrmain[i]<< " "<<endl;
}

这个错误是命名不佳的结果,让我重命名,以便您看到问题:

for(innercounter=0; innercounter<=arrmain.size(); innercounter++)
{
cout <<arrmain[outercounter]<< " "<<endl;
}

现在,应该很清楚您使用了错误的变量来索引向量。这将是最大大小为 2 的向量中的索引 16 和 20。由于这些索引超出了向量的界限,因此您具有未定义的行为。使用正确的索引时,<=还会导致您偏离向量使用<的范围。

除了为您的变量使用更好的名称外,我建议使用基于范围。这从 C++11 开始可用。

for (int value : arrmain)
{
cout << value << " "<<endl;
}

代码中的主要问题是 (1) 在打印其值时使用错误的变量来索引向量,即您使用cout <<arrmain[i]而不是cout <<arrmain[j]; (2) 在迭代到j <= arrmain.size()时超出数组边界(而不是j < arrmain.size().请注意,arrmain[arrmain.size()]超出向量的边界 1,因为向量索引从 0 开始;例如,大小为 5 的向量的有效索引范围从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 中进行了描述。

运行代码后,我发现了两个错误,这些错误在下面的代码中得到了修复。

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++)   // should be < instead of <=
{
cout << arrmain[j] << " " << endl;    // j instead of i
}
}
}

此代码将输出:16 16 20,因为您在每次插入操作后打印矢量元素。您可以在外面进行第二个循环,以避免重复操作。

基本上,向量用于处理动态大小变化的情况。因此,如果要动态增加向量的大小,可以使用 push_back(),如果大小已经预定义,则可以使用 [] 运算符。