If I'm trying to create a Queue in C++, how do I make the Queue of a certain size? - c++

I'm very new to C++ and am rather confused as to how to make a Queue (our first homework assignment).
For the constructor, we're supposed to accept a length that the Queue should be. The Queue's length must in turn be the closest Fibonacci number greater than the given length if it is not already a Fibonacci number. (e.g.: if given 10 in the constructor, make the length 13).
Right now I'm implementing the Queue as an array. Should I have something like int queueContents[]; in the private part of my header, then set it to the closest Fibonacci number in the constructor?
How would I go about declaring it for use throughout the whole file and set its length in my constructor?

You will have a global variable keep track of the size (if you ever needs to grow it for efficiency's sake).
ArrayQueue(int sz)
{
size = getFib(sz);
queueContents = new int[size];
//set front and back to initial value
}
getFib(int sz) {...}
And yes, you need a global variable int *queueContents. (pointer preferred).
Feel free to ask further questions. I recently had to code a basic array-based queue too so (hopefully) I can answer any question you will have. :)

You can calculate the nearest fibonacci number and then have a variable capacity and everytime you insert into the queue, check if this exceeds the capacity..

Related

array of pointers and pointer to an array in c++

i have a class in which it's protected section i need to declare an array with unknown size (the size is given to the constructor as a parameter), so i looked around and found out that the best possible solution is to declare an array of pointers, each element points to an integer:
int* some_array_;
and simply in the constructor i'll use the "new" operator:
some_array_ = new int[size];
and it worked, my question is: can i declare an array in a class without defining the size? and if yes how do i do it, if not then why does it work for pointers and not for a normal array?
EDIT: i know vecotrs will solve the problem but i can't use them on my HW
You have to think about how this works from the compiler's perspective. A pointer uses a specific amount of space (usually 4 bytes) and you request more space with the new operator. But how much space does an empty array use? It can't be 0 bytes and the compiler has no way of knowing what space to allocate for an array without any elements and therefore it is not allowed.
You could always use a vector. To do this, add this line of code: #include <vector> at the top of your code, and then define the vector as follows:
vector<int> vectorName;
Keep in mind that vectors are not arrays and should not be treated as such. For example, in a loop, you would want to retrieve an element of a vector like this: vectorName.at(index) and not like this: vectorName[index]
Lets say that you have an integer array of size 2. So you have Array[0,1]
Arrays are continuous byte of memery, so if you declare one and then you want to add one or more elements to end of that array, the exact next position (in this case :at index 2(or the 3rd integer) ) has a high chance of being already allocated so in that case you just cant do it. A solution is to create a new array (in this case of 3 elements) , copy the initial array into the new and in the last position add the new integer. Obviously this has a high cost so we dont do it.
A solution to this problem in C++ is Vector and in Java are ArrayLists.

Getting size (not length) of c style string in function [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 6 years ago.
How do I, and is it even possible, get actual maximum size of character array passed to a function as a pointer?
int size=0;
while (char_array[size++])
this won't work, as it will return number of characters in the array, and I need its actual size.
Also I cannot use any libraries (specifically string) or my own classes or basically anything useful.
EDIT as it turns out, I will have to explain the assignment quickly. And I am told not to do it in the comments. So here it is:
I have to implement a function that has three character arrays passed as pointers. Cannot change that in any way. First one is a string with commands included in that string (important). The commands are simple: delete x letters, and so on, but some are tricky, like add x letters from second/third character array to the right. Why tricky? Because those arrays may contain more commands, which will then be added to the string I'm working on.
So one way to do it is to work on the string passed to a function, but that would be very slow, and I would have to add/delete characters in the middle, which basically means moving the rest of the letters many times. So I would have to have m*n opertions, where n is size of string and m is ammount of commands. But only n operations if I could write to another string.
However I don't know how much space would I need, because the commands could add more commands, which would add more letters to initial ammount of characters. Checking the ammount and type of commands beforehand would be slow and make the whole thing rather pointless. However I know that the string passed to the function will have enough space (it's in the assignment specifications). So if I just could access it's size, I could declare another string with same size, knowing it would fit the resulf for sure.
So what will I do? I will declare this local string that I'm writing into with initial size and then if the result is greater I will rewrite it to a bigger string. Which will give me n times z operations, where z is a number of rewrites, which is still better than n times m, but worse than just n.
If you can change the function signature, you can use some template magic:
template<int N>
int foo(char (&arr)[N])
{
int size = N;
}
This assumes you actually pass in an array, not a plain pointer.
If you're passing a pointer, you'll also need to pass in the size, or use non-standard hacks (such as inspecting the memory before the actual array, where the size is usually stored)

Advice on how to implement std::vector using a circular array?

I am to write a C++ program that :
"Implements the vector ADT by means of an extendable array used in a circular fashion, so that insertions and deletions at the beginning and end run in constant time. (So not O(n)). Print the circular array before and after each insertion and deletion, You cannot use the STL."
This task seems very confusing to me. A std::vector is implemented using a dynamic array that is based off the concept of a stack, correct? Performing a deletion or insertion at the front seems to me that this should be implemented as a Queue or maybe a Dequeue, not a Vector. Also, a circular array would mean that when data is pushed onto an array that is Full, old data becomes overwritten, right? So when should I know to expand the vector's capacity?
If I'm not making sense here, Basically I need help in understanding how I should go about implementing a dynamic circular array..
Yes, this is a homework assignment. No, I do not expect anyone to provide code for me, I only wish for someone to give me a push in the right direction as to how I should think about implementing this. Thank you.
I think you are actually being asked to implement deque. The point of the "circularity" is that in normal vector you cannot add an element at the beginning since there is no free space and you would have to move all other elements to the right. So what you can do is you simulate a circle by putting the element to the end the base array and remember that's where the first element is.
Example: 2, 3, -, -, 1 where 1 is first and 3 is last
So, basically you insert elements circullary, and remember where the first and the last elements are so you can add to beginning/end in O(1). Also when the array is full, you have to move all the elements to a larger one. If you double the size, you still get amortized time of O(1)
1) m_nextIn and m_nextOut - data attributes of class queue;
I find it useful to have two integers, with label m_nextIn and m_nextOut ... these identify where in the circular array you 'insert' the next (i.e. youngest) obj instance into the queue, and where you 'delete' the oldest obj instance from the queue.
These two items also provide constant time insert and delete.
Don't get confused as to where the beginning or end of the queue is. The array starts at index 0, but this is not the beginning of your queue.
The beginning of your queue is at nextIn (which probably is not 0, but may be). Technique also known as round-robin (a research term).
2) empty and full - method attributes
Determining queue full / empty can be easily computed from m_nextIn and m_nextOut.
3) extendable
Since you are prohibited from using vector (which itself is extendable) you must implement this functionality yourself.
Note about your comment: The "dynamic memory" concept is not related to stack. (another research term)
Extendable issues occur when your user code invokes the 'insert' AND the array is already full. (capture this test effort) You will need to detect this issue, then do 4 things:
3.1) allocate a new array (use new, and simply pick an appropriate size.)
Hint - std::vector() doubles it's capacity each time a push_back() would overflow the current capacity
3.2) transfer the entire contents of the array to the new array, fixing all the index's as you go. Since the new array is bigger, just insert trivially.
3.3) delete the old array - i.e. you copied from the old array to the new array, so do you 'delete' them? or simply delete the array?
3.4) finish the 'insert' - you were in the middle of inserting another instance, right?
Good luck.

C++ Fixed Size Container to Store Most Recent Values

I would like to know what the most suitable data structure is for the following problem in C++
I am wanting to store 100 floats ordered by recency. So when I add (push) a new item the other elements are moved up one position. Every time an event is triggered I receive a value and then add it to my data structure.
When the number of elements reaches 100, I would like to remove (pop) the item at the end (the oldest).
I want to able to iterate over all the elements and perform some mathematical operations on them.
I have looked at all the standard C++ containers but none of them fulfill all my needs. What's the easiest way to achieve this with standard C++ code?
You want a circular buffer. You can use Boost's implementation or make your own by allocating an array, and keeping track of the beginning and end of the used range. This boils down to doing indexing modulo 100.
Without creating your own or using a library, std::vector is the most efficient standard data structure for this. Once it has reached its maximum size, there will be no more dynamic memory allocations. The cost of moving up 100 floats is trivial compared to the cost of dynamic memory allocations. (This is why std::list is a slow data structure for this). There is no push_front function for vector. Instead you have to use v.insert(v.begin(), f)
Of course this assumes what you are doing is performance-critical, which it probably isn't. In that case I would use std::deque for more convenient usage.
Just saw that you need to iterator over them. Use a list.
Your basic function would look something like this
void addToList(int value){
list100.push_back(value);
if(list100.size() > 100){
list100.pop_front();
}
}
Iterating over them is easy as well:
for(int val : list100){
sum += val;
}
// Average, or whatever you need to do
Obviously, if you're using something besides int, you'll need to change that. Although this adds a little bit more functionality than you need, it's very efficient since it's a doubly linked list.
http://www.cplusplus.com/reference/list/list/
You can use either std::array, std::dequeue, std::list or std::priority_queue
A MAP (std::map) should be able to solve your requirement. Use Key as the object and value as the current push number nPusheCount which gets incremented whenever you add an element to map.
when adding a new element to map, if you have less than 100 elements, just add the number to the MAP as key and nPushCount as the value.
If you have 100 elements already, check if the number exists in map already and do following:
If the number already exists in map, then add the number as key and nPushCount as value;
If doesnt, delete the number with lowest nPushCount as value and then add the desired number with updated nPushCount.

Updating the elements of an array(The oldest element will be deleted after a new element has entered to array)

I have a question but I don't know how to search about it, so wanted to ask you.
It may sound simple but I'm a kind of a newbie.
I'm coding in C++. I have 20 values in an array. I do some work on them and after the calculation, I need to add a new value to these 20 values and need to delete the oldest variable. A kind of updating the array with new values.
For example:
My previous values : a,b,c,d, .... t
My current values : b,c,d,e .... u
This process will go on under a loop as long as the condition is not satisfied.
So, my question is: Is there any specific structure or method to perform this task or do I have to handle this work manually ? (Actually, I could do it by writing an impractical method which could be enough for me but I don't think there might not be a dedicated stack structure for this work)
Thanks in advance.
Use std::queue or std::deque(difference that queue is FIFO(first in first out) when deque can remove elements from both sides):
if (queue.size() == MAX_SIZE) {
queue.pop_front();
}
queue.push_back(value);