tbb::parallel_for 将“const value_type”作为“this”参数传递会丢弃限定符

tbb::parallel_for passing ‘const value_type’ as ‘this’ argument discards qualifiers

最近开始学习TBB。我正在尝试使用 TBB 并行实现压缩稀疏行乘法(数据类型 std::complex<int>)。这是我的代码:

struct CSR {
    std::vector<std::complex<int>> values;
    std::vector<int> row_ptr={0};
    std::vector<int> cols_index;
    int rows;
    int cols;
    int NNZ;
};

std::vector<std::complex<int>> tbb_multiply(const CSR& A,
    const CSR& B) { // B here is transpose  
    
    std::vector<std::complex<int>> result(A.rows * B.rows, 0);
    tbb::parallel_for(0,A.rows,[=](int i){
        for (int j = A.row_ptr[i]; j < A.row_ptr[i + 1]; j++) {
            int Ai = A.cols_index[j];
            std::complex<int> Avalue = A.values[j];
            for (int k = 0; k < B.rows; k++) {
                std::complex < int > sum(0, 0);
                for (int l = B.row_ptr[k]; l < B.row_ptr[k + 1]; l++)
                    if (Ai == B.cols_index[l]) {
                        sum += Avalue * B.values[l];
                        break;
                    }
                if (sum != std::complex < int >(0, 0)) {
                    result[i * B.rows + k] = sum;
                }
            }
        }
    });
    return result;
}

编译时出现下一个错误:

error: passing ‘const value_type’ {aka ‘const std::complex’} as ‘this’ argument discards qualifiers [-fpermissive] result[i * B.rows + k] = sum;

您捕获 by-value,这使得 result const(因为默认情况下 lambda 不是 mutable)。由于您的目标也是 return result,我建议您改为捕获 by-reference

tbb::parallel_for(0, A.rows,[&](int i){
//                           ^