【问题标题】:What's the bug in the following code?以下代码中的错误是什么?
【发布时间】:2010-03-29 13:12:05
【问题描述】:
#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, " "));
}

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

【问题讨论】:

  • @Tom:对不起,我是 C++ 新手;我需要一段时间才能熟悉 STL 中的所有边缘情况。
  • 什么是“令人毛骨悚然的分段错误”?

标签: c++ stl boost segmentation-fault


【解决方案1】:

当您调用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));

【讨论】:

  • 最好是v2.reserve(v.size()),然后是transform
猜你喜欢
  • 1970-01-01
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多