C++'s min_element() not working for array [closed]

℡╲_俬逩灬. 提交于 2019-12-14 03:29:54

问题


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;
}

I get the error invalid conversion from 'unsigned int*' to 'unsigned int' [-fpermissive]. What am I missing here?


回答1:


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);

Note, that you should also check the result of reading from std::cin:

if (std::cin >> n >> a >> b) {
   // process the values
}

... and, of course, it seems you're leaking the memory allocated for w.



来源:https://stackoverflow.com/questions/23871658/cs-min-element-not-working-for-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!