在线编译器中的细分故障
下面的代码在GDB和VS代码中正常工作,但其他在线编译器不断投掷“分段故障”。有人可以帮我吗?我试图解决的每个问题,我都会遇到此错误。
例如: 给出了一系列整数。在数组中查找反转计数。
反转计数:对于数组,反转计数指示数组与分类的距离(或关闭)。如果数组已经排序,则反转计数为0。如果以相反顺序对数组进行排序,则反转计数为最大值。
形式上,如果a [i]> a [j]和i< j。
代码:
long long int inversionCount(long long arr[], long long N) {
vector<long long> v;
long long int count = 0;
for (int i = 0; i < N; i++) v[i]= arr[i];
auto min = min_element(arr, arr+ N);
auto max = max_element(arr, arr+ N);
swap(v[0], *min);
v.erase(max);
v.push_back(*max);
for (int i = 0; i < N; i++) {
if(v[i] > v[i+1]) {
swap(v[i],v[i+1]);
count++;
}
return count;
}
}
The code below works fine in gdb and VS code but other online compilers keep throwing "segmentation fault". Can anyone please help me with this? Every question I try to solve I keep getting this error.
For example:Given an array of integers. Find the Inversion Count in the array.
Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0. If an array is sorted in the reverse order then the inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Code:
long long int inversionCount(long long arr[], long long N) {
vector<long long> v;
long long int count = 0;
for (int i = 0; i < N; i++) v[i]= arr[i];
auto min = min_element(arr, arr+ N);
auto max = max_element(arr, arr+ N);
swap(v[0], *min);
v.erase(max);
v.push_back(*max);
for (int i = 0; i < N; i++) {
if(v[i] > v[i+1]) {
swap(v[i],v[i+1]);
count++;
}
return count;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在这里有很多问题。首先,您尝试使用
v
中的元素,而无需为它们分配空间(即,即使其大小仍然是v
的元素, 。零
元素 先前指向的任何点,以及集合的结尾。
迭代器或引用元素
max
You have a number of problems here. For one, you try to use elements in
v
without ever allocating space for them (i.e., you're using subscripts to refer to elements ofv
even though its size is still zero elements. I'd usually use the constructor that takes two iterators to copy an existing collection (and pointers can be iterators too).Assuming you fix that, this:
... invalidates
max
and every other iterator or reference to any point between the elementmax
previously pointed to, and the end of the collection. Which means that this:...is attempting to dereference an invalid iterator, which produces undefined behavior.