Container of fixed dynamic size

后端 未结 3 758
离开以前
离开以前 2020-12-15 16:11

Is there a standard container for a sequence of fixed length, where that length is determined at runtime. Preferrably, I\'d like to pass an argument to the constructor of ea

3条回答
  •  情歌与酒
    2020-12-15 16:51

    Theoretically vector has the properties you need. As you noted, actions that possibly do assignments to the contained type, including especially any sequence modifications (empace_back, push_back, insert etc.) are not supported if the elements are noncopyable and/or nonassignable. So to create a vector of noncopyable elements, you'd have to construct each element during vector construction.

    As Steve Jessop points out in his answer, if you define the vector const in the first place you won't even be able to call such modifying actions - and of course the elements remain unchanged as well.

    If I understand correctly, you have only a sequence of constructor arguments, not the real object sequence. If it's only one argument and the contained type has a corresponding constructor, things shoule be easy:

    struct C
    {
      const int i_;  
      C(int i) : i_(i) {}
    };
    
    int main()
    {
      const std::vector theVector { 1, 2, 3, 42 };
    }
    

    If the constructor is explicit, you have to make a list first or explicitly construct the objects in the initializer-list:

    int main()
    {
      auto list = { 1, 2, 3, 4 };
      const std::vector theVector (std::begin(list), std::end(list));
      const std::vector anotherVector { C(1), C(44) };
    }
    

    If it's more than just one argument per constructed object, consider a intermediate creator object:

    struct C
    {
      const int i_;  
      C(int i, int y) : i_(i+y) {}
    };
    
    struct CCreator
    { 
      int i; int y; 
      explicit operator C() { return C(i,y); }
    };
    
    int main()
    {
      const std::vector ctorArgs = { {1,2}, {3,42} };
      const std::vector theVector { begin(ctorArgs), end(ctorArgs) };
    }
    

提交回复
热议问题