C++中std::transform的使用问题

普拉纳夫·乔杜里

在解决与运算符重载相关的问题时,我遇到了一个问题。我现在将描述问题的具体情况。

代码包含一个名为的类Matrix,定义如下:

class Matrix {
   public:
    std::vector<std::vector<int>> a;
    friend Matrix operator+(const Matrix& x, const Matrix& b);
};

我应该通过重载+运算符来找到两个矩阵的相加

最初,我决定使用该transform函数来执行两个矩阵的相加,并提出了以下代码,该代码不会为所有测试用例生成正确答案,

Matrix operator+(const Matrix& x, const Matrix& y) {
    Matrix result;
    result.a.reserve(x.a.size());
    for (size_t i = 0; i < x.a.size(); i++) {
        std::transform(x.a.at(i).begin(), x.a.at(i).end(), y.a.at(i).begin(),
                       std::back_inserter(result.a[i]), std::plus<int>());
    }
    return result;
}

因此,我被迫使用嵌套的 for 循环执行相同的任务,这会为所有测试用例生成正确的答案,如下所示:

Matrix operator+(const Matrix& x, const Matrix& y) {
    Matrix result;
    std::vector<int> vec;
    result.a.reserve(x.a.size());
    for (size_t i = 0; i < x.a.size(); i++) {
        vec.reserve(x.a.at(i).size());
        for (size_t j = 0; j < x.a.at(i).size(); j++) {
            vec.push_back(x.a.at(i).at(j) + y.a.at(i).at(j));
        }
        result.a.push_back(vec);
        vec.clear();
    }
    return result;
}

我没有看到transform版本有什么问题有人能指出代码中的错误吗?任何帮助表示赞赏。谢谢。

迈克尔·维克斯勒

未定义的行为。元素保留但未添加到向量中:

result.a.reserve(x.a.size()); // result.a is still empty
for (size_t i = 0; i < x.a.size(); i++) {
    std::transform(x.a.at(i).begin(), x.a.at(i).end(), y.a.at(i).begin(),
                   std::back_inserter(result.a[i] /* UB */ ), std::plus<int>());
}

result.a.resize()改为打电话

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++中std :: vector的内存问题

C ++中std :: cin和isdigit的问题

使用 std::views 将 std::vector<string> 转换为 C++20 中的 std::string

与std :: condition_variable wrt相比使用std :: atomic的方法暂停并恢复C ++中的std :: thread

“使用namespace:std;”的功能是什么?在C ++中?

C ++ 17中不推荐使用的std :: is_literal_type

在C ++中实现HashMap时如何使用std :: function

尝试使用 STD C++ 中的“cyl_bessel_i”

C ++:创建线程中的问题;错误C2672:'std :: invoke':找不到匹配的重载函数

使用g ++ 8和c ++ 20的std :: async的编译问题

std :: transform中的分段错误

使用自己的迭代器,Visual Studio中的std :: transform失败

使用 ?: as if 语句在 C++ 中的问题

C++ 中的 std::ws 与 std::skipws

C ++中的std :: vector与std :: array

C ++中的std :: promise和std :: future

在std :: ofstream中复制std :: cout(C ++)

现实生活中的应用程序中是否使用C ++中的某些std类?

使用c + = expression和c = c + expression时输出中的std :: string差异

尝试使用std :: functional和std :: bind在C ++中创建C#样式事件访问修饰符

C ++ std :: list插入问题

C ++ std :: wofstream unicode问题。

在VSCode中调试C ++期间将输入传递给std :: cin的问题

问题 c++ 中的 std::cout 流究竟是如何工作的?

使用std :: transform求向量

代码中的C ++ STD错误

什么是C ++中的std :: invoke?

关于C ++中的std:cout

等价于C中的std :: pair