C++ STL: Can arrays be used transparently with STL functions?

后端 未结 11 1333
半阙折子戏
半阙折子戏 2020-12-15 17:07

I was under the assumption that STL functions could be used only with STL data containers (like vector) until I saw this piece of code:

#include         


        
11条回答
  •  情深已故
    2020-12-15 18:10

    the STL has it hidden stuff. Most of this works thanks to iterators, consider this code:

    std::vector a = {0,1,2,3,4,5,6,7,8,9};
    // this will work in C++0x use -std=c++0x with gcc
    // otherwise use push_back()
    
    // the STL will let us create an array from this no problem
    int * array = new int[a.size()];
    // normally you could 'iterate' over the size creating
    // an array from the vector, thanks to iterators you
    // can perform the assignment in one call
    array = &(*a.begin());
    
    // I will note that this may not be considered an array
    // to some. because it's only a pointer to the vector.
    // However it comes in handy when interfacing with C
    // Instead of copying your vector to a native array
    // to pass to a C function that accepts an int * or
    // anytype for that matter, you can just pass the
    // vector's iterators .begin().
    
    // consider this C function
    extern "C" passint(int *stuff) { ... }
    
    passint(&(*a.begin())); // this is how you would pass your data.
    
    // lets not forget to delete our allocated data
    delete[] a;
    

提交回复
热议问题