簡體   English   中英

在C ++中通過初始化數組初始化向量時出現分段錯誤

[英]Segmentation fault while initializing vector by an initialized array in C++

我想在C ++的算法庫中使用sort() 我只能找到僅對向量進行排序的示例,因此我試圖通過初始化的數組來初始化向量。 執行時,我遇到了段錯誤,無法在我編寫的代碼中找出問題所在。

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
int n,k,packet[1000],min=0;
scanf("%d",&n);
scanf("%d",&k);

for (int i = 0; i < n; ++i)
{
    scanf("%d",&packet[i]);
    cout<<i<<endl;
}
cout<<"debug";
vector<int> packets(packet,packet+n);
vector<int>::iterator start,stop;
sort(packets.begin(),packets.begin()+n);

min=*(packets.begin())- *(packets.end());
cout<<min;
for (vector<int>::iterator it=packets.begin(); it!=packets.end()-k; ++it)
{
    printf("%d  ",*it );
    if((*(it+k) - *it)<min)
    {
        start=it;
        stop=it+k;
    }
}
printf("%d\n",*stop- *start );

return 0;

}

*(packets.end())

packets.end()返回在向量的最后一個元素之后的元素的迭代器。

嘗試取消引用會導致未定義的行為。

注釋說明您可以對數組進行排序(如果您查看http://en.cppreference.com/w/cpp/algorithm/sort,您會發現該sort采用兩個參數: -RandomIt must meet the requirements of ValueSwappable and RandomAccessIterator. 。普通指針可以滿足此要求)。

在您的示例中,發生段錯誤是因為您嘗試取消引用valid but undereferencable迭代器( min=*(packets.begin())- *(packets.end());的“ end()”返回的迭代器min=*(packets.begin())- *(packets.end()); 。基本上,它返回指向向量的最后一個元素after的迭代器。如果要使迭代器到達向量的最后一個元素,則可以使用rbegin()但是當然需要確保向量首先為空。

通過在調試器下運行代碼,您可以很容易地看到這一點,您會發現分段錯誤sort調用無關

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM