Reputation: 2853
I have the following
static const unsigned int chromosome = 6;
double bestFitness[chromosomes];
for(int i = 0; i < chromosomes; i++){
bestFitness[i] = estimateFitness(currPopultaion[i]);
}
int best1 = 0;
best1 = max_element(bestFitness, bestFitness + chromosomes) - bestFitness;
.......
The IDE seems to be throwing a warning "Implicit conversion loses integer precision:'long' to 'int'"
Also upon inspecting the value of best1, it seems to be always assigned to 0 upon compilation.
I am currently not able to understand if the max_element() function is invoking as expected.
Upvotes: 0
Views: 135
Reputation: 477030
The difference of two pointers has type std::ptrdiff_t
, which is signed and may be a wider type than int
. You should change the type of best1
to std::ptrdiff_t
.
You can also use std::distance
to compute the distance, from <iterator>
:
std::ptrdiff_t best1 = std::distance(
bestFitness,
std::max_element(bestFitness, bestFitness + N));
Chances are of course that you could rewrite your code in terms of iterators and give up on indexes altogether.
Note also that in general the returned iterator could be past-the-end if the input range is empty. This doesn't happen in your case (since arrays always have non-zero size), but in more general settings that's something you need to account for.
Also note that you don't need to remember the array size; it's part of the type and can be obtained via begin
/end
, also from <iterator>
:
std::max_element(std::begin(bestFitness), std::end(bestFitness));
Upvotes: 2