这是我报名参加的Coursera算法课程中的一个问题。这不是为了询问问题的答案,但我根本没有解决它,因为我的代码(在函数中(运行到for
循环行之前的行,然后它退出。这是代码:
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using namespace std;
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
double value = 0.0;
vector<int> rates;
int len = end(weights) - begin(weights);
cout << "pre-loop (values loop)" << endl; //the last line the code executes
for (int i = 0; i < len; i++){
rates[i] = values[i] / weights[i];
cout << values[i] / weights[i] << endl;
}
std::sort(begin(rates), end(rates), greater<int>());
return value;
}
int main() {
int n;
int capacity;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cin >> values[i] >> weights[i];
}
double optimal_value = get_optimal_value(capacity, weights, values);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
文件本身由讲师提供,我们只需要使用我们正在处理的函数,而不需要使用main
函数。
明确使用push_back
是一种解决方案;不过,就变体而言,我要注意的是,在这种情况下,您可以很容易地从现有的vector
之一初始化新的vector
(从int
到double
的类型转换工作得很好(,然后以大致相同的方式进行计算,而不是逐个构建元素:
double get_optimal_value(int capacity, const vector<int>& weights, const vector<int>& values) { // Arguments made into const references to avoid pointless copies
double value = 0.0;
vector<double> rates(std::begin(values), std::end(values)); // Initialize to copy of values converted to double
const auto len = weights.size(); // No need for iterator arithmetic; size tells you the size
cout << "pre-loop (values loop)" << endl; //the last line the code executes
for (size_t i = 0; i < len; i++){
rates[i] /= weights[i]; // No need to use values anymore
cout << rates[i] << endl;
}
std::sort(begin(rates), end(rates), greater<int>());
return value;
}
#include <iostream>
#include <vector>
#include <algorithm>
//using std::vector; // why this and you're using std in the next line
using namespace std;
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {//capacity is unused
double value = 0.0, temp{};
vector<double> rates;
//int len = end(weights) - begin(weights); //using .size() instead
cout << "pre-loop (values loop)" << endl;
for (int i = 0; i <weights.size(); i++)
{
temp = static_cast<double>(values[i]) / static_cast<double>(weights[i]);
rates.push_back(temp);
cout << static_cast<double>(values[i]) / static_cast<double>(weights[i]) << endl; //to get the floating number because you're dividing
}
std::sort(begin(rates), end(rates), greater<double>());
return value;
}
int main() {
int n;
int capacity;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++)
{
std::cin >> values[i] >> weights[i];
}
double optimal_value = get_optimal_value(capacity, weights, values);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
你不能像以前那样给向量加一个值,因为它的大小为null,你必须把它放大,这样你才能加值。我对你的代码(评论(做了一些更正
但是您仍然会得到0作为函数的返回,因为在get_optimal_value()
的执行过程中值不会改变。
你必须更具体,这样我们才能帮助你