C ++的min_element()不工作的数组 [英] C++'s min_element() not working for array
问题描述
我试图找到在C ++中数组的一个子集的最小元素如下:
I am trying to find the minimal element of a subset of an array in c++ as follows:
#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;
using std::min_element;
void load_values(int n);
unsigned *w;
int main() {
int n, a, b;
cin >> n >> a >> b;
w = new unsigned[n];
load_values(n); // sets values to w[i]
int min = min_element(w+a, w+b);
}
void load_values(int n) {
while(n--)
w[n] = 1;
}
我得到的错误从无效的转换无符号整数*'到'无符号整型[-fpermissive]
。缺少什么我在这里?
推荐答案
请注意,该的std :: min_element()
返回一个迭代到最低值,而不是价值本身。我怀疑你仅基于上述code这个错误:假设正确包括指令和使用指令的code编译OK虽然将打印的最小元素的地址,而不是它的价值。最有可能你的实际code看起来更像
Note, that std::min_element()
returns an iterator to a minimal value, not the value itself. I doubt that you get this error based on the above code alone: assuming proper include directives and using directives the code compiles OK although it would print the address of the minimum element rather than its value. Most likely your actual code looks more like
unsigned min = std::min_element(w + a, w + b);
请注意,您也应该检查从的std :: CIN
读取结果:
Note, that you should also check the result of reading from std::cin
:
if (std::cin >> n >> a >> b) {
// process the values
}
......,当然,您似乎泄漏分配给内存是W
。
这篇关于C ++的min_element()不工作的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!