【发布时间】:2015-02-27 01:56:14
【问题描述】:
我编写了以下代码,用于根据我的排序标准对两个向量进行排序:
typedef pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > Elem;
bool bucketComparator(const Elem& a, const Elem& b) {
//find the min and max of "a" and "b"
// return true if a should go before b in the sort
unsigned minA,maxA;
unsigned minB,maxB;
if((a.second.first).size()<=1){
minA=maxA=*((a.second.first).begin());
} else{
minA=*std::min_element((a.second.first).begin(),(a.second.first).end());
maxA=*std::max_element((a.second.first).begin(),(a.second.first).end());
}
if((b.second.first).size()<=1){
minB=maxB=*((b.second.first).begin());
} else{
minB=*std::min_element((b.second.first).begin(),(b.second.first).end());
maxB=*std::max_element((b.second.first).begin(),(b.second.first).end());
}
if((minA<=minB)&&(maxA<=maxB)){
return true;
} else{
return false;
}
}
main()
{
vector<Elem> A;
//initializing vector A with values
std::sort(A.begin(), A.end(), bucketComparator);
//further computation using vector A
}
错误:大数据的分段错误。
当向量 A 的大小为 223080 或更大时,我发现出现分段错误。但是当向量 A 的大小小于 100 时,代码运行良好。我无法理解其原因,因为我在 64GB RAM 上运行代码。有人可以帮我解决这个问题吗?
此外,当我在 linux 上运行 top 命令时,我发现程序在停止之前甚至没有消耗 0.1%(64GB)的可用 RAM,因为分段错误。
我什至尝试通过首先使用 std::sort 和冒泡排序对向量进行排序来找到最大值和最小值——但我仍然遇到同样的错误。
我正在运行以下版本的 gcc:gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
有什么方法可以让我编写我的程序,以便它根据我在:bucketComparator 中使用的排序标准对大向量进行排序。我对 c 和 c++ 都很好。
此外,当我执行简单的 std::sort: 时,代码不会给出分段错误:
std::sort(A.begin(), A.end());
【问题讨论】:
-
您将应用程序编译为什么? 64位还是32位?如果您只能访问 2-4GB 的 RAM,那么 RAM 的数量将无济于事。
-
(a.second.first).size()(或 b)是否有可能为 0,所以您在我认为不好的情况下取消引用空向量上的begin()) -
您没有提供严格的弱排序。如果
minA = minB和maxA = maxB,则bucketComparator( a, b )和bucketComparator( b, a )都返回true,这是不允许的。请参阅here 了解更多信息。 -
@StegVerner 将
minA <= minB ...更改为minA < minB ...,或者可能保留minA<=minB,但将第二部分更改为maxA<maxB。只要确保它遵循我上面提供的链接中描述的规则。 -
@StegVerner 你是什么意思?你正在对它们进行分类,一个必须在另一个之前。如果对于两个值
a和b,f(a,b)和f(b,a)都返回false,则它们被认为是等效的,并且它们之间的顺序不能保证。如果您希望它们与原来的顺序相同,可以使用std::stable_sort。