krej
krej

Reputation: 468

Can you use the size of a vector as a length of an array?

I have an std::vector defined as:

std::vector<glm::vec3> faces;

And I want to use the size of that vector as the length of an array of floats. Right now I'm trying to do it like this:

float vertices[faces.size()][3];

But I keep getting errors saying that you must use a constant value. I thought maybe it was because the size of the vector can change, so I tried this instead:

const int size = faces.size();
float vertices[size][3];

But I still get the same error. Is it possible to do this?

Upvotes: 1

Views: 1205

Answers (4)

wheaties
wheaties

Reputation: 35970

The problem you're facing is that you're attempting to use a non-constant expression to create the size of the array at compile time. The vector::size is a runtime operation. In the second example, while you might think you're being clever the compiler is more than likely optimizing that variable away and deducing that you are, in fact, using some quantity which will be known only at runtime.

Unless you're having to integrate with a C library or something legacy (I see you're using OpenGL calls which are C) I'd advise you to look at Boost::multi_array. Hence,

boost::multi_array<float,2> myFloats(boost::extents[myVector.size()][3]);

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

Why do you want to use a C array anyway? A vector would be much more apt here.

vector<vector<float> > vertices(faces.size(), vector<float>(3));

And if you already know the size of the inner vector and its size is fixed, it’s a safe bet that a struct would be better suited than a vector here:

struct vertex {
    float x;
    float y;
    float z;
};

vector<vertex> vertices(faces.size());

The usefulness of C-style vectors is severely limited in C++. The only use is basically if you know their size (and usually also the contents) at compile-time and use them as a glorified constant. For everything else, there exist better containers. And even this niche is filled in the next standard by std::array.

Upvotes: 4

ThomasMcLeod
ThomasMcLeod

Reputation: 7769

You cannot define an array of objects on the stack (aka automatic variables) with a non-constant array size. The size of the array must be know at compile time. How else would the compiler know what much stack space to reserve for the array?

If you want an array where the size is not determined until runtime, you must use the new operator to define the array on the heap.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

Not in standard C++ (although I believe some compilers offer it as a non-standard language extension).

You could do something like:

float (*vertices)[3] = new int[faces.size()][3];

Note that this has now been allocated on the heap, so you'll need to delete [] vertices at some point.

Upvotes: 2

Related Questions