c++ - 如何初始化STL容器中存在的类的数据?

标签 c++ stl

例如,我有 A 类:

 class A{
           int value_;
           public:
           A(A& a){
                value_ = a.value_;
           }
           A(int value){
                value_ = value;
           }
 };

我想要一个 A 类 vector ,但我想将所有 vector 的值传递给 A(int value)

 std::vector<A,allocator<A>> my_vector;
  • 最好的方法是什么?
  • 有没有办法使用分配器?

最佳答案

With the new standard added functionality was granted to objects of Allocator type.

One of the features added was that Allocators now allows emplacement construction, aka. construction of objects using a constructor other than copy/move.


template< class U, class... Args > void construct( U* p, Args&&... args );

The standard does guarantee that STL containers must use this new feature, and with that said you could implement your own allocator just for the purpose of default initializing a non-default-initializable object.


It's not the prettiest solution, but whatever floats your boat..

The allocator has nothing to do with that part of object initialization, it's only purpose is to allocate/deallocate memory, the type of initialization you are referring to is done elsewhere.

The only constructor an allocator will call is the copy-constructor when someone asks it to perform a placement-new, and the value passed to that copy-ctor has already been established somewhere else.

To sum things up; No, you cannot use an allocator so solve this particular problem.


std::vector 什么时候需要使用default-ctor

std::vector仅在两种情况下使用它拥有的类型的默认构造函数:

  1. 您指定 std::vector 的元素数量在适当的构造函数重载中,但提供默认值

  2. 您使用 std::vector<T>::resize (n)并增加容器中对象的数量(注意没有指定成员函数的第二个参数)


考虑到上述内容,我们可以使用容器做很多事情,而无需在我们的对象中提供默认构造函数,例如将其初始化为包含 N 个值为 X 的元素.

struct A{
  A (A const& a)
   : value_ (a.value_) 
  { } 

  A (int value)
    : value_ (value)
  {}  

  int value_;
};

int
main (int argc, char *argv[])
{
  std::vector<A> vec (5, A(1)); // initialize vector with 5 elements of A(1)

  vec.push_back (A(3));         // add another element
}

但是我真的很想能够使用vec.resize()!?

然后你有、四个选项:

  1. 使用分配器的 C++11 方法

  2. 让你的对象有一个默认构造函数

  3. 用一个非常薄的包装器包装您的对象,其唯一目的是默认初始化包含的对象(这在某些情况下说起来容易做起来难)

  4. “在 boost::optional 中包装 [对象] 实际上可以为任何类型提供默认构造函数” - @ Xeo

关于c++ - 如何初始化STL容器中存在的类的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11502601/

相关文章:

c++ - 读取文件并保存完全相同的文件c++

c++ - 对结构 vector 进行两次排序

C++初始化对映射

c++ - 如何在 C++ 中读取不断增长的文本文件?

c++ - 尾随返回类型和右值

C++ 和转换运算符

c++ - 使用 C++ 替换 snprintf 和 printf

c++ - Qt,从 qApp->processEvents() 中排除事件

c++ - std::copy 到 std::cout 用于 std::pair

c++ - 为什么在这个函数中返回时使用std::move