How to get the address of the std::vector buffer start most elegantly?

后端 未结 11 2147
-上瘾入骨i
-上瘾入骨i 2020-12-03 18:12

I want to use std::vector for dynamically allocating memory. The scenario is:

int neededLength = computeLength(); // some logic here

// this will allocate t         


        
11条回答
  •  有刺的猬
    2020-12-03 18:35

    The reason it looks ugly is because you're at the borderline of nice and clean C++ style code and nice and clean C style code. The C++ code uses iterators, the C code uses pointers and sizes.

    You could create some glue to circumvent these problems:

    template< typename at_Container, typename at_Function >
    void for_container( at_Container& c, at_Function f ) {
        f( &c[0], c.size() );
    }
    

    and call it in the client code.

    void afunction( int* p, size_t n ) { 
       for( int* p = ap; p != ap+n; ++p ) {
         printf( "%d ", *p );
       }
    }
    
    void clientcode() {
       std::vector ints(30,3);
       for_container( ints, afunction );
    }
    

提交回复
热议问题