1

I really need some help... I detail my problem, I need an array of a certain type, but I don't know its length before having retrieving values from other arrays, using for structures. In fact, I don't want to spend time passing again the several loops, and i wonder the best way to do this. Should I use a stack and a counter, and after filling it, instanciate and fill the array ?

RelAttr *tab; //need to initialize it but how /*several for loops retrieving values*/ tab[i] = value; /*end for loops*/ 

Obviously this code is incomplete, but it is how stuff is done. And i know i can't do the affectation without having specified the array length before...

Thanks for your help

4 Answers 4

4

Just use a std::vector.

std::vector<RelAttr> vec; vec.push_back(a); vec.push_back(b); ... 

It manages its own growth transparently. Every time it grows, all the items are copied, but the amortized cost of this is O(1).

The storage is also guaranteed to be contiguous, so if you really need a raw C-style array, then you can simply do this:

const RelAttr *p = &vec[0]; 

However, you should really only do this if you have a legacy C API that you need to satisfy.

Sign up to request clarification or add additional context in comments.

3 Comments

okay, exactly what I need, and with the fact that it is contiguous, it helps... yeah I need a raw array... because it is a requirement. nonsense
@getmax0 Beware though, in older C++ standards, there doesn't seem to to be any guarantee for an std::vector to store things contiguously in memory (see for example groups.google.com/group/comp.lang.c++/msg/…)
@getmax0 Also, another side note, the vector will own the memory, so don't let it go out of scope while you need the array pointer to be valid.
1

As this is C++, suggest using a std::vector (std::vector<RelAttr>) as the number of objects is not required to be known beforehand. You can use std::vector::push_back() to add new elements as required.

2 Comments

as I need an array to pass to a function in the end, the transformation would be to "copy" in the end the vector in the array ?
See @OliCharlesworth answer, he provides a solution to this. Or, you could copy the vector to an array but seems pretty inefficient.
0

The easiest way (assuming nothing exceptionally performance critical) is to use a std::vector to assemble the values and (if needed) convert the vertor to an array. Something like;

std::vector<RelAttr> vec; ... vec.push_back(value); ... 

and if you want to convert it to an array afterwards;

RelAttr *tab = new RelAttr[vec.size()]; copy( vec.begin(), vec.end(), a); 

Comments

0

If you don't know length at compiling time you can use

function malloc, operator new, vector or another type of container

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.