最近遇到了一个很奇葩的问题,STL中的vector设置为全局变量的时候,当对vector进行扩充时,总会在运行时
出现问题,见下面的代码:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
#define max 1000
class Node {
public:
int flag; //1->shop,2->buyer,0->access,-1->can't move
int x;
int y; //buyer need
long long cost, val;
Node()
{
x = 0;
y = 0;
flag = 0;
val = 0;
}
Node(int xx, int yy, int f, int v)
{
x = xx, y = yy, flag = f, val = v;
}
};
int vis[max][max] = { 0 };
int n = 1, m = 0, k = 0, d = 0;
vector<vector<Node> > a(n, vector<Node>(n, Node()));
queue<Node>que;
struct Direction {
int x;
int y;
}Direct[4] = { (-1,0),(1,0),(0,1),(0,-1) };
bool Check(int x, int y, vector<vector<Node> > &a)
{
if (x < 0 || x > n || y > n || y < 0)
{
return false;
}
if (a[x][y].flag == -1 || vis[x][y])
{
return false;
}
return true;
}
int main()
{
long long ans = 0;
int x = 0, y = 0;
long long z = 0;
cin >> n >> m >> k >> d;
//vector<vector<Node> > a(n, vector<Node>(n, Node()));
for (int i = 0; i < m; ++i)
{
cin >> x >> y;
a[x][y].x = x;
a[x][y].y = y;
a[x][y].flag = 1;
que.push(a[x][y]);
}
for (int i = 0; i < k; ++i)
{
cin >> x >> y >> z;
a[x][y].flag = 2;
a[x][y].x = x;
a[x][y].y = y;
a[x][y].cost += z;
}
for (int i = 0; i < d; ++i)
{
cin >> x >> y;
a[x][y].flag = -1;
a[x][y].x = x;
a[x][y].y = y;
}
while (!que.empty())
{
Node temp = que.front();
que.pop();
int nx = temp.x, ny = temp.y, val = temp.val;
vis[nx][ny] = 1;
for (int i = 0; i < 4; ++i)
{
int tx = nx + Direct[i].x;
int ty = ny + Direct[i].y;
if (!Check(tx, ty,a))
{
continue;
}
a[tx][ty].x = tx;
a[ty][ty].x = ty;
a[tx][ty].val = val + 1;
vis[tx][ty] = 1;
que.push(a[tx][ty]);
if (a[tx][ty].flag == 2)
{
ans += a[tx][ty].cost*(val + 1);
}
}
}
cout << ans << endl;
system("pause");
return 0;
}
问题应该是出现在67行到70行之间对vector进行填充时的自动扩充,运行时的错误如下:
该程序将vector设置为局部变量时(即main函数内部62行处取消注释,再将全局的vector注释掉),程序没有问题,能正常运行成功。我很好奇这个到底是什么原因:在main函数内部对全局vector扩充会出问题,而对它自己内的局部vector扩充正常工作?是否是因为在对全局vector进行扩充时,vector新分配的内存空间的位置是在堆上(vector的内部实现是通过一个指针,指向内已分配的内存空间来实现的。但是为什么刺出全局区指针指向堆会出现问题呢。正常情况下不应该都是正常的吗?),而不是在全局区对vector进行扩充的?但是为什么下面这个程序又能正常运行呢?
#include<iostream>
using namespace std;
int *p = NULL;
int *p1 = new int();
int main()
{
p = new int();
*p = 4;
delete p1;
p1 = NULL;
cout << *p <<endl;
return 0;
}
这个涉及到了在main函数中对全局指针进行操作(重新分配内存和释放内存),和我们的预期是一致的。
后来仔细阅读代码的时候发现,在67行到70行处,直接就对vector的下标进行了取下标运算,而此时vector很有可能还没有进行扩张,所以就会出现非法访问内存的问题,解决办法就是在64行之前,根据输入的n强制调用vector的resize()函数重设vector的大小。代码如下(加在64行之前):
a.resize(n);
for(int i = 0; i < n ; ++i)
{
a[i].resize(n);
}