c++ - 将可被数字整除的数字插入 vector 中

标签 c++ vector

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

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

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

#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 in clang .

挑出最重要的:

source.cpp:8:10: warning: declaration shadows a local variable [-Wshadow]

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

source.cpp:6:26: warning: unused variable 'i' [-Wunused-variable]

vector arrmain; int 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;
}

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

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

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

关于c++ - 将可被数字整除的数字插入 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55883187/

相关文章:

c++ - 如何在不使用 '..' 的情况下包含与当前源文件不在同一目录中的 C++ 头文件?

C++ 检查类对象是否包含某个元素

java - 如何将角度转换为 vector

c++ - 为什么 C++ 用零初始化 std::vector 而不是 std::array?

c++ - Windows 上有用的开源库/项目

c++ - mysql_query() 很慢

c++ - 在 C++ 中使用邻接表在图中添加边

c++ - 检查元素是否在两个 vector 中的最快方法

c++ - vector 会导致错误共享吗

c++ - boost 或 C++11 是否具有与 tbb::queuing_mutex 和 tbb::spin_mutex 相同的互斥锁?