在做这个 codility课时,我遇到了一些奇怪的行为。
int solution(std::vector<int> &A) {
std::vector<int> B, C;
B.resize(std::count_if(A.begin(), A.end(), [](int x){return x < 0;}));
C.resize(A.size() - B.size());
std::copy(A.begin(), std::remove_copy_if(A.begin(), A.end(), B.begin(), [](int x){return x > 0;}), C.begin());
std::sort(A.begin(), A.end(), [](int x, int y){return x > y;});
std::sort(B.begin(), B.end(), [](int x, int y){return x < y;});
std::sort(C.begin(), C.end(), [](int x, int y){return x > y;});
这部分函数将一个向量分成两个向量,第一个是正整数,第二个是负整数。然后按所需顺序对所有向量进行排序。
if (B.size() >= static_cast<size_t>(2)) {
if (C.size() >= static_cast<size_t>(3)) {
if (B[0] * B[1] > C[1] * C[2])
return B[0] * B[1] * C[0];
} else if(C.size() == static_cast<size_t>(2)) {
if (B[0] * B[1] > C[0] * C[1])
return B[0] * B[1] * C[0];
}
}
return A[0] * A[1] * A[2];
}
这部分从输入向量中找到 3 个元素的最大乘积。
到达返回后,函数崩溃,我得到一个错误:
a.out: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) &&
old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) &&
((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted
我试图调试它,我看到在 return 语句之后调试器跳转到 B & C 向量声明,然后跳转到退出的大括号。我从未见过像那样的东西,我想了解它。我在 linux 下使用 g++-7.1 并使用 --std=c++14 标志进行编译。提前致谢。