C++ - 二进制表达式的无效操作数

标签 c++ sorting stl

我正在尝试使用 std::sort对结构列表进行排序。但我收到错误:

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

结构:

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

主要功能:

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

我想按 cpu_cylcles 值升序对列表中的所有进程项进行排序。我还制作了 compare_pid 函数,它接受两个进程并返回一个 bool 值。我不知道错误是什么。有人可以帮忙吗?

最佳答案

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

好吧,第三行代码在 std::sort 的某处.唯一的运营商是+ .所以有错误的表达式是__first+1其中 __firstlist<process>::iterator .列表迭代器没有 iterator+int重载,因为它们是双向迭代器,但不是随机访问。

你不能调用 std::sortstd::list 上.使用 std::vector相反,或者另一个带有随机访问迭代器的容器。

关于C++ - 二进制表达式的无效操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175025/

相关文章:

c++ - C++ STL 中 max_element 和 minmax_element 的行为差异

c++ - 在 apache 上运行 C++ cgi 程序?

c++ - 在cmake文件中使用edje_cc

python - 对于给定的 Pandas df,按列对 df 进行排序(首先是最高的求和值),然后在每个唯一值顺序中按另一列排序

java - 如何识别属于最大堆的元素和属于最小堆的元素?

PHP - 按字母顺序排序并将值分配给特定变量

c++ - 从多个线程更改共享变量 C++

c++ - FORTRAN 中函数的基本结构是什么?

c++ - std::按成员查找对象

c++ - 为 std::map 定义一个使用值而不是键的比较函数