我有一个极简主义的交通模拟器:它是元胞自动机,分四步工作:
- 加速度(+1 速度单位)
- 刹车安全性(-到下一辆车的空格数)
- 随机打破,模拟司机的不完美(-1 或 -0 随机),
- 移动(+汽车细胞的速度)
在 vector<vehicule*>
的初始化过程中,我在移动过程中遇到了段错误它不会进入 vector 的构造函数。
但是当删除破坏安全程序时,我没有任何段错误。如果道路尺寸小于 16,我没有。
这里是获取错误的最少代码
#include <iostream>
#include <vector>
using namespace std;
struct vehicule
{
vehicule(int v);
int vitesse;//speed
static int vMax;
};
vehicule::vehicule(int v)
{ vitesse=v; }
int vehicule::vMax=5;
void avancer(std::vector<vehicule*>&);//each car mooves their value of speed, of square on the road.
void freinage_secu(std::vector<vehicule*>& );//each car slow down the number of cases betwen their and the next car.
void add_veicule(std::vector<vehicule>&, std::vector<vehicule*>& );
void afficher_route(std::vector<vehicule*>& road)
{
for (vehicule* v:road)
{
if (v==nullptr)
{ cout<<"-"; }
else
{ cout<<"x"; }
}
cout<<"\n";
}
void freinage_secu(vector<vehicule*> &road)
{
int lng=road.size();
int nbV=0;
int last;
int j=0;
for (unsigned int i=0;i<road.size();i++)//compter le nombres de vehicules
{
if(road[i]!=nullptr)
{
nbV++;
}
}
while(road[(j%lng)]==nullptr)//on se place sur le premier evicule
{ j++; }
for (int i=0;i<nbV;i++)
{
last=j;
do
{
j++;
}while(road[j%lng]==nullptr);
if(road[last]->vitesse>(j+lng-last-1)%lng)
{
road[last]->vitesse=(j+lng-last-1)%lng;
}
}
}
void avancer(vector<vehicule*> &road)
{
vector<vehicule*> road2(road.size(),nullptr);//<<<--the bug comme there
for (unsigned int i=0;i<road.size();i++)
{
if (road[i]!=nullptr)
{
road2[(i+road[i]->vitesse)%road.size()]=road[i];
}
}
road=road2;
}
void add_veicule(vector<vehicule> &V, std::vector<vehicule*>& road)
{
unsigned int i=0;
bool overload=1;
V.push_back(vehicule::vMax-vehicule::vMax/2);
while(road[i]!=nullptr&& i<road.size())
{
i++;
}
if (i<road.size())
{
road[i]=&V[V.size()-1];
overload=0;
}
if (overload)
{
V.pop_back();
cout<<"la route est saturée\n";
}
}
/// --------------------------------main
int main()
{
int nbV=16;//dont'bugs if it is lower than 16 (we can overload the road), bugs if <= 16
vector<vehicule> ensembleV;
vector<vehicule*> road(nbV,NULL);//the road is a ring.
string commande;
bool continuer=true;
add_veicule(ensembleV, road);
while(continuer)
{
freinage_secu(road);//slow down
avancer(road);//move foward
afficher_route(road);
cout<<"que voulez vous faire ?\n v\tincrémenter le nombre de vehicules\n quit\tquiter la simulation.\n";
cin>>commande;
if(commande=="v")
{
add_veicule(ensembleV, road);
}
if(commande=="quit")
{
continuer=false;
}
}
return 0;
}
我将 road 和 ensembleV 放到全局空间,段错误仍然存在。
最佳答案
这个:
vector<vehicule*> road(nbV,NULL);//the road is a ring.
应该是:
vector<vehicule*> road(nbV, nullptr);//the road is a ring.
似乎你的编译器在欺骗你......在其余部分它对我有用,没有错误,即使使用 nbV = 1
关于c++ - vector 构造函数中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22683651/