Reputation: 13590
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 ptr have all the addresses of what ever other vectors??
Upvotes: 2
Views: 2414
Reputation: 23896
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.
Upvotes: 0
Reputation: 145457
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
Upvotes: 1
Reputation: 6233
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.
Upvotes: 1