2016-03-27 32 views
0

在下面的代碼中,我發現了一個用於揹包問題的貪婪算法的分段錯誤。我以前從來沒有成功解決過分段錯誤,儘管我已經看到它們,所以我會很感激一些幫助。loop-malloc.c向量中的分段錯誤:沒有這樣的文件或目錄

我運行調試器時得到的消息是沒有「malloc.c」。當我運行valgrind時,出現「無效的大小爲4的讀取」。在這個和bug的性質之間,我猜測我試圖訪問一個不存在的向量元素。但我嘗試了所有我能想到的方法來試圖確保在遍歷向量時循環沒有超越其邊界。我沒有使用C++ 11基於範圍的for循環,但仍然得到相同的錯誤。它似乎並不重要,我爲for循環的參數選擇它,它仍然會拋出分段錯誤)。

在此先感謝。

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <stdlib.h> 

using namespace std; 

bool decreaseSort(int a, int b) 
{ 
    return a > b; //sort by decreasing value for better performance 
} 

double get_optimal_value(int capacity, vector<int> weights, vector<int> values) { 

sort(weights.begin(),weights.end(), decreaseSort); 
sort(values.begin(),weights.end(), decreaseSort); 

vector<int> ourKnapsack(values.size(), 0); 

double totalValue = 0.0; 
int ourInput = 0; 

for (auto i : ourKnapsack){ 
    int ourValue = values.at(i); 
    int ourWeight = weights.at(i); 
    double unitValue = (double)ourValue/ourWeight; 
    if (capacity == 0) 
     return totalValue; 


    if (weights.at(i) < capacity){ 
     ourInput = weights.at(i); 
    } 
    else { 
     ourInput = capacity; 
    } 


    totalValue = totalValue * (ourInput * unitValue); 
    weights.at(i)-=ourInput; 
    ourKnapsack.at(i)+=ourInput; 
    capacity-=ourInput; 

} 
return totalValue; 
} 

    int main() { 
    int n = 3; 
    int capacity = 50; 

    vector<int> values(n); 
    values = {60,100,120}; 
    vector<int> weights(n); 
    weights = {20,50,30}; 

    double optimal_value = get_optimal_value(capacity, weights, values); 

    std::cout.precision(10); 
    std::cout << optimal_value << std::endl; 
    return 0; 
} 
+0

我完全專注於處理矢量和循環的代碼,因爲我看到了「分割」這個詞,但卻忽視了排序......謝謝。 – Anonymous

+0

這就是「未定義行爲」的含義。這並不意味着「立即分段故障」。這意味着「從現在開始,任何事情都可能發生」。立即分段錯誤將是一種可能性。隨着時間的推移,稍後再吹起來的代碼也是另一種可能性,也被完全限定爲「未定義的行爲」。歡迎來到C++。 –

回答

2
sort(values.begin(),weights.end(), decreaseSort); 

那是你的問題,就在那裏。哎呀。

顯然,它應該是values.end()而不是weights.end()

相關問題