Casting problems

Jan 27, 2016 at 1:34am
I'm trying to do operations using members of struct looping through it. But I always get a casting error.

My struct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  struct Chromosome {
    std::string sChromoName;
    int sWSA;
    double sFC;
  };
  std::vector<Chromosome> chromosomes;

auto MaxWSA = std::max_element( chromosomes.begin(),                    chromosomes.end(),
                                     []( const Chromosome &a, const Chromosome &b )
                                     {
                                         return a.sWSA < b.sWSA;
                                     } );

        double fitness = 0.0;

        for(unsigned int i = 0; i < chromosomes.size(); i++){
            fitness = 0.5 * (double)(MaxWSA - chromosomes[i].sWSA)/MaxWSA + 0.5 * (chromosomes[i].sFC/100.0);
            probability.emplace_back(chromosomes[i].sChromoName, fitness);
        }


I'm trying to get the maximum value of the sWSA member and do some operations. But it give me the following error:

error: invalid cast from type ‘__gnu_cxx::__normal_iterator<Chromosome*, std::vector<Chromosome> >’ to type ‘double’|

I am really lost here, how can this be fixed? Thank you.
Jan 27, 2016 at 3:10am
Does it say what lines give you the error?
Jan 27, 2016 at 3:19am
closed account (E0p9LyTq)
Your MaxWSA assignment, you are retrieving an iterator.
http://www.cplusplus.com/reference/algorithm/max_element/

Try int MaxWSA = *std::max_element(/* function parms */);

Jan 27, 2016 at 8:23am
FurryGuy wrote:
Try int MaxWSA = *std::max_element(/* function parms */);
Nope, the typ an iterator to Chromosome: std::vector<Chromosome>::iterator.


if chromosomes is empty the result is invalid (=chromosomes.end()). So you need to check that.

Line 17 would look like this:

fitness = 0.5 * (double)(MaxWSA->sWSA - chromosomes[i].sWSA)/MaxWSA->sWSA + 0.5 * (chromosomes[i].sFC/100.0);

Assumed that you want to use sWSA
Jan 27, 2016 at 1:01pm
pnoid: The error is in line 17.

FurryGuy: I still have errors with *std::max_element, because of the type. They differ from int to Chromosome.

coder777: That's it. You solved my problem. Thank you. Just one question:

MaxWSA->sWSA

This means I am creating a new .sWSA member in the struct with the MaxWSA value, or just assigning the correct type to MaxWSA for the operation?
Last edited on Jan 27, 2016 at 1:02pm
Jan 27, 2016 at 3:23pm
This means I am creating a new .sWSA member in the struct with the MaxWSA value, or just assigning the correct type to MaxWSA for the operation?
I don't get it.

The iterator (from max_element) references (similiar to a pointer) a certain element in the vector. When you change it it will change the element in the vector.
Jan 27, 2016 at 10:40pm
Thanks for clarifying everything.
Topic archived. No new replies allowed.