Containers that doesn't change member address

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int * ptr;

	vector<int> data;
	data.resize( 1000 );

	for( int i = 0; i < 1000; ++ i )
	{
		data[i] = i;
	}

	ptr = &data[30];

	for( int i = 1000; i < 10000; ++ i ){
		if( ptr != &data[30] ){
			cout << "This pointer is no longer valid" << endl;
			ptr = &data[30];
		}

		data.push_back( 300 );
	}

	return 0;
}


so I kinda need container that doesn't rellocate their address
It doesn't need to be like vector
that everything is in a single pointer
such as

 
int * a = new int[2000];


I have a pointer pointing to a member of a container and it needs to remain valid...

doing
1
2
3
4
5
6
7
8
9
10
11
vector<int *> Array;

// allocating
for( int i = 0; i < 1000; ++ i ){
   Array.push_back( new int(i) );
}

// deallocating
for( int i = 1000; i--; ) delete Array[i];

Array.clear();


kinda waste of time, allocating them
and deallocate them seem to take some time too

a List is also not efficient enough
because I access them based on index

It is not a int it is pointing to but a texture, for the sake of simpler example I pick int


So is there a container that doesn't change member address and allocate when it needs to expand ?
Last edited on
Sounds like you might want std::deque.

A mistake in your first example: You probably meant to use resize instead of reserve.
Last edited on
My bad with my wrong example

Hmmm, I look into deque and change my code to

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <deque>

using namespace std;

int main()
{
	int * ptr;
	deque<int> data;

	for( int i = 0; i < 1000; ++ i )
	{
	    data.push_back(i);
	}

	ptr = &data[30];

	for( int i = 1000; i < 10000; ++ i ){
		if( ptr != &data[30] ){
			cout << "This pointer is no longer valid" << endl;
			ptr = &data[30];
		}

		data.push_back( 300 );
	}

	return 0;
}


Yes, it seems to work
but somehow it took around 2 seconds to do this,

Is my code use deque in a wrong way ?
Looks correct. std::deque is usually implemented by storing the data in many small fixed-sized arrays instead of one big array. That can make adding elements slower because it has to allocate memory more often, but on the other hand it doesn't have to reallocate and copy elements like std::vector so it depends. Accessing elements by index will probably be a little slower using std::deque because it has to do more work doing some calculations on the index and an extra array access. The deallocation also probably slower because it has to deallocate many arrays, instead of one big array.
Topic archived. No new replies allowed.