views:

165

answers:

1
#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, " "));
}

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

+12  A: 

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));
James McNellis
And best is probably to `v2.reserve(v.size())` first before a `transform`.
GMan