开发者

c++ convert matrix into row pointer vector

vector<vector<int> > mymatrix;
vector<int> *ptr_vec;

How do I make the ptr_vec point to the vectors which are inside mymatrix one after another. In more details Let's say mymatrix.at(0).size() gives 10, and mymatrix.at(1).size() gives 14 ..if I go ptr_vec->at(15) it should give me the fifth member in mymatrix.at(1) hope it doesn't confuse anybody.

ok now that I showed the point , think of mymatrix as separated vectors like this vector<int> row1, row2, row3; which might be simpler still how to make that pt开发者_C百科r have all the addresses of what ever other vectors??


Given your clarification "how to make that ptr have all the addresses of what ever other vectors" I think you placed the * incorrectly in your declaration.

It think you meant ptr_vec to be a vector of pointers.

If so, ...

#include <iostream>
#include <vector>
#include <stddef.h>
using namespace std;

typedef ptrdiff_t Size;

template< class Elem >
Size countOf( vector< Elem > const& v ) { return v.size(); }

int main()
{
    vector< vector<int> >   mymatrix( 10, vector<int>( 14 ) );
    vector<int*>            ptr_vec;

    for( Size i = 0;  i < countOf( mymatrix );  ++i )
    {
        vector<int>&    v   = mymatrix[i];

        for( Size j = 0;  j < countOf( v );  ++j )
        {
            ptr_vec.push_back( &v[j] );
        }
    }

    // Init data
    for( Size i = 0;  i < countOf( mymatrix );  ++i )
    {
        vector<int>&    v   = mymatrix[i];

        for( Size j = 0;  j < countOf( v );  ++j )
        {
            v[j] = 100*i + j + 1;
        }
    }

    // Display
    for( Size i = 0;  i < countOf( ptr_vec );  ++i )
    {
        cout << *ptr_vec[i] << ' ';
    }
    cout << endl;
}

Cheers & hth.,

– Alf


You will have to manually iterate through the matrix to construct the vector:

vector<int> *ptr_vec = new vector<int>;
for (int j=0;j<mymatrix.size();j++) {
  for (int k=0;k<mymatrix[j].size();k++) {
    vec->push_back(mymatrix.at(j).at(k));
  }
}

I think what you want is not possible, because your matrix does not exist as a contiguous block of ints, it is a block of vectors, each of which point to another memory location for each row.


You can use std::vector<T>::pointer:

vector<vector<int> > mymatrix;
vector<vector<int> >::pointer ptr = &mymatrix[0];

You can now deference ptr, use pointer arithmetics, etc., just like any pointer.

For more information, see e.g. MSDN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜