How to convert vector to array

后端 未结 10 1541
野的像风
野的像风 2020-11-22 09:20

How do I convert a std::vector to a double array[]?

相关标签:
10条回答
  • 2020-11-22 09:30

    Vectors effectively are arrays under the skin. If you have a function:

    void f( double a[]);
    

    you can call it like this:

    vector <double> v;
    v.push_back( 1.23 )
    f( &v[0] );
    

    You should not ever need to convert a vector into an actual array instance.

    0 讨论(0)
  • 2020-11-22 09:31
    vector<double> thevector;
    //...
    double *thearray = &thevector[0];
    

    This is guaranteed to work by the standard, however there are some caveats: in particular take care to only use thearray while thevector is in scope.

    0 讨论(0)
  • 2020-11-22 09:35

    You can do some what like this

    vector <int> id;
    vector <double> v;
    
    if(id.size() > 0)
    {
        for(int i = 0; i < id.size(); i++)
        {
            for(int j = 0; j < id.size(); j++)
            {
                double x = v[i][j];
                cout << x << endl;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:37

    There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:

    std::vector<double> v;
    double* a = &v[0];
    
    0 讨论(0)
  • 2020-11-22 09:39

    If you have a function, then you probably need this:foo(&array[0], array.size());. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.

    0 讨论(0)
  • 2020-11-22 09:42

    For C++11, vector.data() will do the trick.

    0 讨论(0)
提交回复
热议问题