[英]std::sort is setting array pointer to null
我正在尝试使用std::sort
函数订购随机生成的数组,如下所示:
int *p = new int[n];
for (int i=0; i < n; ++i) {
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(1, 6);
p[i]= uniform_dist(e1);
}
// Prints array (ok)
for (int i=0; i < n; ++i)
{
std::cout << p[i] << ' ';
}
std::cout << std::endl;
// P != NULL at this point
std::sort(&p, &p + n);
// P == NULL at this point
你知道为什么会这样吗?
std::sort(&p, &p + n);
该行导致未定义的行为。 &p
是本地p
指针对象的地址, 而不是该对象指向的数组的位置。 然后, &p + n
使用本地对象的地址执行非法的指针算术运算。
您应该这样做:
std::sort(p, p + n);
当然,所有这些最终都是徒劳的,因为无论如何您都应该只使用std::vector
,然后它变成:
std::sort(begin(v), end(v));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.