向量(push_back); g++ -O2;分段错误
我在向量方面遇到问题(在使用push_back时),但它仅在使用额外的g++标志-O2(我需要它)时出现。
#include <cstdio>
#include <vector>
typedef std::vector<int> node;
typedef std::vector<node> graph;
int main()
{
int n, k, a, b, sum;
bool c;
graph g(n, node());
c = scanf("%i%i", &n, &k);
for(int i=0; i<n; i++)
{
sum=2;
for(int j=0; j<i; j++)
sum*=2;
for(int j=0; j<sum; j++)
{
if(j%2==0)
c = scanf("%i", &a);
else
{
c = scanf("%i", &b);
a += b;
g[i].push_back(a); //---------------LINE WHICH CAUSES SEGMENTATION FAULT
}
}
}
for(int i=n-2; i>=0; i--)
{
for(size_t j=0; j<g[i].size(); j++)
{
if(g[i+1][(j*2)] >= g[i+1][(j*2)+1])
g[i][j] = g[i+1][j*2];
else
g[i][j] = g[i+1][(j*2)+1];
}
}
printf("%i\n", g[0][0]);
return 0;
}
I'm having problem with vector, (in the usage of push_back) but it only appears when using additional g++ flag -O2 (I need it).
#include <cstdio>
#include <vector>
typedef std::vector<int> node;
typedef std::vector<node> graph;
int main()
{
int n, k, a, b, sum;
bool c;
graph g(n, node());
c = scanf("%i%i", &n, &k);
for(int i=0; i<n; i++)
{
sum=2;
for(int j=0; j<i; j++)
sum*=2;
for(int j=0; j<sum; j++)
{
if(j%2==0)
c = scanf("%i", &a);
else
{
c = scanf("%i", &b);
a += b;
g[i].push_back(a); //---------------LINE WHICH CAUSES SEGMENTATION FAULT
}
}
}
for(int i=n-2; i>=0; i--)
{
for(size_t j=0; j<g[i].size(); j++)
{
if(g[i+1][(j*2)] >= g[i+1][(j*2)+1])
g[i][j] = g[i+1][j*2];
else
g[i][j] = g[i+1][(j*2)+1];
}
}
printf("%i\n", g[0][0]);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你有:
以相反的顺序。就目前而言,用于调整图形大小的变量“n”未初始化。
I think you have:
in the reverse order. As it stands, the variable 'n' which you use to size graph is not initialised.
在输入操作之前使用
n
初始化向量意味着您正在调用可怕的未定义行为。正如此处所述,程序可以在此之后执行任何操作。Initializing the vector with
n
before the input operation means you're invoking the dreaded Undefined Behavior. As stated here, the program is allowed to do anything after that.如果您初始化
n
,效果会很好,正如我在评论中已经提到的那样。将第一行更改为:Works perfectly if you initialize
n
as I already mentioned in my comment. Change the first lines to: