向量不push_back整数
The vector doesn't push_back the integer
我写了一个简单的程序来生成素数。质数打印出来很好。我还试图将每个素数放入一个向量中进行进一步处理,但不知怎的,这些数字似乎没有进入(即push_back)向量,因为它打印出奇怪的数字而不是素数。总之,整个程序工作正常,只有矢量有问题。请帮助。
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
const int NUM = 300;
int main()
{
int i, j ;
int counter = 0;
bool arr[NUM] = {false}; //false == 0
vector<int> aVector;
...
cout << "nNumber of prime numbers is " << counter << endl;
for (j=0; j<aVector.size() ; j++)
{
cout << "aVector[" << j << "] is " << aVector[j] << endl;
}
return 0;
}
您的代码访问超出arr
的范围。数组在c++中是零索引的。
for (i = 2; i<=NUM; i++)
应为:for (i = 2; i<NUM; i++)
for (j = 1; j <= NUM/i; j++)
应为:for (j = 1; j * i < NUM; j++)
应用这些修复后,你的代码似乎为我工作。我删除了if (i
检查,因为它是多余的。
正如M.M指出的那样,在代码中的许多地方,您试图从arr
数组的边界外获取和设置值。这是c++中未定义的行为。一旦调用未定义的行为,任何都可能发生——整个程序的行为(不仅仅是包含错误的行)是不可预测的。在静态数组的边界外写入通常会导致覆盖其他变量。
看起来你的程序覆盖了aVector
的内部数据,用其他东西替换了它的指针一个动态分配的数组。难怪它会输出"随机垃圾"——vector现在认为它的内容在内存中的不同位置。
作为经验法则:简单的C[]数组是邪恶的,使用向量代替:vector<bool> arr(NUM, false)
。访问一个元素使用:arr.at(some_index)
。如果some_index
在向量边界之外,这将抛出异常。注意,arr[some_index]
不执行边界检查,即使你使用向量,因此也可能导致未定义的行为。
这是一个简单的快速修复。循环到vector的末尾。
for (j=0; j<aVector.size() && j < 6; j++){
cout << "aVector[" << j << "] is " << aVector[j] << endl;
}
------------------------ 完整的代码,我试着
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
using namespace std;
#define NUM 100
int main()
{
int i, j ;
int counter = 0;
bool arr[NUM] = {false}; //false == 1
vector<int> aVector;
for (i = 2; i<=NUM; i++)
{
if (arr[i] == 0)
{
cout << setw(6) << i ; //i is a prime number
/****doesn't seem to work****/
aVector.push_back(i); //fill the vector with prime numbers
counter++;
if (i <= NUM/2)
{
for (j = 1; j <= NUM/i; j++)
{
arr[i*j] = 1;
}
}
}
}
cout << "nNumber of prime numbers is " << counter << endl;
/*** it prints out strange numbers ******/
for (j=0; j<aVector.size() && j < 6 ; j++){
cout << "aVector[" << j << "] is " << aVector.at(j) << endl;
}
return 0;
}
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何在C++中将整数转换为其数字数组