开发者

What's the bug in the following code?

开发者 https://www.devze.com 2022-12-24 06:42 出处:网络
#include <iostream> #include <algorithm> #include <vector> #include <boost/array.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/array.hpp>
#include <boost/bind.hpp>

int ma开发者_如何学编程in() {
  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, " "));
}

When run, this gives a creepy segmentation fault. Please tell me where I'm going wrong.


v2 has a size of zero when you call transform. You either need to resize v2 so that it has at least as many elements as v before the call to transform:

v2.resize(v.size());

or you can use std::back_inserter in the call to transform:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号