0

I declared a global struct with the following structure:

typedef struct {
    int value;
    int index;
}element;

I have a program with k sorted queues, and I put in a heapSort(I am using an array) the minimum from each one. I use the index value in struct to track the element that I want to pop out of the heap. Now, I want to test the program for different number of queues, so I did this:

for (int i = 10;i <= 50;i += 10) {
    const int k = i;
    element a[k];
}

But I get an error:

Expression must have a constant value

Is there any way I can "trick" that?

4
  • 1
    Standard C++ does not have variable length arrays (C does). Use std::vector instead. Commented Apr 3, 2017 at 21:21
  • 2
    You might use std::vector<element> a(k). Commented Apr 3, 2017 at 21:21
  • 1
    std::vector<element> a(i); and throw out k entirely. And fyi, if allowed by whatever purpose this is for, the heap operations in <algorithm> will come in very handy and save you a ton of code. If this is for a priority queue, the std::priority_queue adapter can save you even more effort. Commented Apr 3, 2017 at 21:22
  • See msdn.microsoft.com/en-us/library/zb1574zs.aspx Commented Apr 3, 2017 at 21:48

1 Answer 1

1

You declared an array, an array's size cannot be changed. To solve this issue it would be in your best interest to use a vector.

Try this:

#include <vector>
vector <element> a(50);

To pop elements out of the vector try this:

a.erase(a.begin()+index_from_zero);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.