循环malloc.c的矢量分段错误:没有这样的文件或目录
Segmentation fault in vector for loop-malloc.c: No such file or directory
我在下面的代码中遇到了背包问题贪婪算法的分段错误。我以前从未成功地解决过分割故障,尽管我见过它们,所以我很感激你的帮助。
当我运行调试器时得到的消息是没有"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;
}
sort(values.begin(),weights.end(), decreaseSort);
这就是你的问题,就在那里。哎呀。
显然,它应该是values.end()
,而不是weights.end()
。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 如果没有malloc,链表实现将失败
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- 解析 csv 文件,"malloc: *** error for object 0x7ffeeb4f4b80: pointer being freed was not allocated"出现此错误
- 循环malloc.c的矢量分段错误:没有这样的文件或目录
- 哪些文件包含malloc()和new()的实现
- 包含malloc声明的头文件的名称是什么?