ChaniLastnamé
ChaniLastnamé

Reputation: 533

C++ - invalid operands to binary expression

I am trying to use std::sort to sort a list of structs. But I am getting the error:

invalid operands to binary expression ('std::__1::__list_iterator<process, void *>' and 'int') __sort3<_Compare>(__first, __first+1, __j, __comp);

Struct:

struct process {
   int process_id;
   int cpu_cycles;
   int mem_footprint;
};

Main function:

int main() {

    list<process> process_list;

    init_process_list(process_list);
    sort(process_list.begin(), process_list.end(), compare_pid);

}

init_process_list:

void init_process_list(list<process> &p_list) {

    cout << "\n>> Generating process list...";

    generator generate; // Random number generator class
    process p;

    for(int i = 0; i < process_count; i++) {
        p.process_id = i;
        p.cpu_cycles = generate.rand_num_between(cycle_lbound, cycle_ubound);
        p.mem_footprint = generate.rand_num_between(mem_lbound, mem_ubound);
        p_list.push_back(p);
    }

    cout << "Done" << endl;

}

compare_pid:

bool compare_pid(process &lhs, process &rhs) { 
    return lhs.cpu_cycles < rhs.cpu_cycles;  
}

I want to sort all the process items in the list by their cpu_cylcles value in the ascending order. I also made the compare_pid function which takes in two process and returns a boolean. I can't figure out what the error is. Can someone please help?

Upvotes: 1

Views: 6566

Answers (1)

Mooing Duck
Mooing Duck

Reputation: 66922

invalid operands to binary expression
('std::__1::__list_iterator' and 'int')
__sort3<_Compare>(__first, __first+1, __j, __comp);

Alright, that third line of code is somwhere in std::sort. The only operator there is +. So the expression with the error is __first+1 where __first is a list<process>::iterator. List iterators do not have a iterator+int overload, because they are bidirectional iterators, but NOT random access.

You cannot call std::sort on a std::list. Use a std::vector instead, or another container with random access iterators.

Upvotes: 3

Related Questions