Designer <vector></vector>



  • I'd like to write a class designer who, as a parameter, accepts a static mass (indicator 1 element) and initiates a vector inside the class with this mass:

    class A
    { 
      public:
        explicit A(int x[]):v(x,x+sizeof(x)/sizeof(*x)) {} // или (int* x)
      private:
        vector<int> v;
    };
    

    It doesn't work... What's the problem?



  • Your designer has a type. int *♪ Therefore, the expression

    sizeof(x)/sizeof(*x)
    

    equivalent

    sizeof( int * )/sizeof( int )
    

    It may be 2 if the size of the indicator is equal, for example, to 8 Baitamas, and the size of the object int Four bikes, or one if the dimensions match.

    It's better to announce two overloaded designers.

    The first designer may be defined as

    A( const int *first, const int *last ) : v( first, last ) {}
    

    a The second designer may be defined either

    A( const int *first, size_t n ) : v( first, first + n ) {}
    

    or use a propulsion device

    A( const int *first, size_t n ) : A( first, first + n ) {}
    

    Also, you can declare a template designer, like,

    template <size_t N>
    A( const int ( &a )[N] ) : v( a, a + N ) {}
    

    This is a demonstration program that shows all three ways to call class designers.

    #include <iostream>
    #include <vector>
    

    struct A
    {
    A( const int *first, const int *last ) : v( first, last ) {}
    A( const int *first, size_t n ) : v( first, first + n ) {}
    template <size_t N>
    explicit A( const int ( &a )[N] ) : v( a, a + N ) {}

    std::vector&lt;int&gt; v;
    

    };

    int main()
    {
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    A a1( a, a + sizeof( a ) / sizeof( *a ) );
    
    for ( int x : a1.v ) std::cout &lt;&lt; x &lt;&lt; ' ';
    std::cout &lt;&lt; std::endl;
    
    A a2( a, sizeof( a ) / sizeof( *a ) );
    
    for ( int x : a1.v ) std::cout &lt;&lt; x &lt;&lt; ' ';
    std::cout &lt;&lt; std::endl;
    
    A a3( a );
    
    for ( int x : a1.v ) std::cout &lt;&lt; x &lt;&lt; ' ';
    std::cout &lt;&lt; std::endl;
    

    }

    Her withdrawal to the console

    0 1 2 3 4 5 6 7 8 9
    0 1 2 3 4 5 6 7 8 9
    0 1 2 3 4 5 6 7 8 9




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2