C++ 什么是分配器<;T>;在向量中,如何使用它?

C++ 什么是分配器<;T>;在向量中,如何使用它?,c++,C++,这是我第一次在vectors中使用分配器函数,我遇到了下面的代码。我想知道它到底想做什么 编辑 我做了一些修改建议,当我运行下面的代码时,我得到一个错误如下..为什么我得到这个 。/../../../../test\u idct.cpp:38:62:从此处实例化 /proj/xbuilds/2017.4_0206_1/installs/lin64/Vivado/2017.4/lnx64/tools/gcc/bin//lib/gcc/x86_64-unknown-linux-gnu/4.6.3/.

这是我第一次在vectors中使用分配器函数,我遇到了下面的代码。我想知道它到底想做什么

编辑 我做了一些修改建议,当我运行下面的代码时,我得到一个错误如下..为什么我得到这个

。/../../../../test\u idct.cpp:38:62:从此处实例化
/proj/xbuilds/2017.4_0206_1/installs/lin64/Vivado/2017.4/lnx64/tools/gcc/bin//lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/stl_vector.h:206:20:错误:没有匹配“std::vector::”的成员:。\u Base{aka std::\u vector:\u-Base}::\u-vector::\u-Base}::::\u-assign
/proj/xbuilds/2017.4_0206_1/installs/lin64/Vivado/2017.4/lnx64/tools/gcc/bin//lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/stl_vector.h:207:20:错误:没有匹配“std::vector::”的成员:。\u Base{aka std::\u vector:\u-Base:{aka std::\u-vector:\u-Base:}:
/proj/xbuilds/2017.4_0206_1/installs/lin64/Vivado/2017.4/lnx64/tools/gcc/bin//lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/stl_vector.h:209:20:错误:没有匹配“std::vector::”u Base{aka std:::”u vector:”u-Base{aka std::”u-vector:”u-Base:”的成员:
../../../test_idct.cpp:在函数“int main()”中:
代码:
模板
结构对齐的分配程序{
类型定义T值\u类型
T*分配(标准::大小\u T数量){
void*ptr=nullptr;
if(posix_memalign(&ptr,4096,num*sizeof(T)))
抛出std::bad_alloc();
返回重新解释(ptr);
}
无效解除分配(T*p,std::size\u T num){
自由基(p);
}
};
int main(){
std::矢量源_块(64*块);
std::矢量源_q(64);
标准::矢量黄金分割(64*块);
}

您不是以C++11的身份编译。这就是为什么会出现这些错误。请注意,这可以在C++03中完成,只需使用旧式类型别名:
typedef T value\u type哇,在C++11及以后的版本中实现分配器变得如此简单了吗?我仍然需要在我的工作场所支持C++03,而且有点落后,但我们不再需要重新绑定、构造、销毁、地址等?只需
allocate
deallocate
以及
value\u类型的别名就可以了?@TeamUpvote:是的,这些现在是可选的,由
allocator\u traits提供回退实现
template <typename T>
struct aligned_allocator {
  typedef T value_type

  T* allocate(std::size_t num) {
    void* ptr = nullptr;
    if (posix_memalign(&ptr,4096,num*sizeof(T)))
      throw std::bad_alloc();
    return reinterpret_cast<T*>(ptr);
  }

  void deallocate(T* p, std::size_t num) {
    free(p);
  }
};

int main() {
  std::vector<int16_t,aligned_allocator<int16_t>> source_block(64*blocks);
  std::vector<uint16_t,aligned_allocator<uint16_t>> source_q(64);
  std::vector<int16_t,aligned_allocator<int16_t>> golden_vpout(64*blocks);
}