【问题标题】:for_each bind vector of vector resizefor_each 绑定向量的向量调整大小
【发布时间】:2011-01-26 20:56:34
【问题描述】:

这是我的第一个问题。我放弃了,将为此使用手卷函子,但我很好奇它应该如何完成。下面的人为示例旨在通过用空值填充向量中的所有向量,将它们的大小调整为 9。指示的行会导致 MinGW GCC 4.5.0 出现大量模板错误。我尝试了几种不同的排列,但只在下面发布了我认为“最接近正确”的代码。应该怎么写?注意,我想保留 resize 的两个参数版本。

#include <vector>
using std::vector;
#include <algorithm>
using std::for_each;
#include <tr1/functional>
using std::tr1::bind;
using std::tr1::placeholders::_1;

int main() {
 vector<vector<void *> > stacked_vector(20);
 for_each(stacked_vector.begin(),stacked_vector.end(),
  bind(&std::vector<void *>::resize,_1,9,0/*NULL*/));  // voluminous error output
 return 0;
}

非常感谢您的意见。

【问题讨论】:

    标签: function bind member tr1


    【解决方案1】:

    很难说没有看到错误输出(坦率地说,即使有它)。但是,尝试将 NULL 作为void* 类型传递:static_cast&lt;void*&gt;(0)。否则,bind 返回的对象会尝试将 int 值作为第二个参数提供给resize

    【讨论】:

    • Amnon 的回答对我有用。对于任何寻找仿函数方法的人,我做了以下操作: template class resize_functor { public: resize_functor(size_t size,T value) : size_(size), value_(value){};模板 void operator()(C & container){ container.resize(size_,value_); } 私人:size_t size_; T值_; }; ... for_each(stacked_vector.begin(),stacked_vector.end(),resize_functor(9u,0));
    【解决方案2】:

    试试这个。

    #include <functional> 
    #include <algorithm> 
    #include <iostream> 
    #include <vector>
    
    
    int main() 
    { 
        typedef std::vector<int> vec_int;
        typedef std::vector<vec_int> vec_vec_int;
    
        // Do this to make the   _1    work
        using namespace std::placeholders; 
    
        static const int FIRST_DIM = 5;
        static const int SECOND_DIM = 10;
        static const int DEFAULT_VALUE = 66;
    
        vec_vec_int v(FIRST_DIM);
    
        std::for_each(v.begin(), v.end(), 
            std::bind(&vec_int::resize, _1, SECOND_DIM, DEFAULT_VALUE));
    
        std::cout << v[4][9];
    
        return (0); 
    } 
    

    如果不想指定默认值,则不需要。

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      相关资源
      最近更新 更多