gpt4 book ai didi

c++ - 以下代码中的错误是什么?

转载 作者:太空狗 更新时间:2023-10-29 23:34:35 24 4
gpt4 key购买 nike

#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/array.hpp>
#include <boost/bind.hpp>

int main() {
boost::array<int, 4> a = {45, 11, 67, 23};
std::vector<int> v(a.begin(), a.end());
std::vector<int> v2;
std::transform(v.begin(), v.end(), v2.begin(),
boost::bind(std::multiplies<int>(), _1, 2));
std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, " "));
}

运行时,这会产生令人毛骨悚然的段错误。请告诉我哪里出错了。

最佳答案

当您调用 transform 时,

v2 的大小为零。您需要调整 v2 的大小,以便在调用 transform 之前它至少具有与 v 一样多的元素:

v2.resize(v.size());

或者您可以在 transform 的调用中使用 std::back_inserter:

std::transform(v.begin(), v.end(), std::back_inserter(v2), boost::bind(std::multiplies<int>(), _1, 2));

关于c++ - 以下代码中的错误是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2538078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com