Coding - practical 11 Flashcards
What is a vector?
A vector is a special type of array that does not have a fixed size, instead elements can be continuously added and the vector will resize automatically.
How do you declare a vector type?
std::vector noteVector;
How do you add data to a vector?
- use the class method push_back(), like so: noteVector.push_back(60);
What happens each time we call push_back()?
The supplied value gets added to end of the list.
How can you set the initial size of a vector?
- You can set the initial size of a vector using the class method resize and supplying a new size. noteVector.resize(10);
When should you use an array vs vector?
Array: - When you can determine the size - 'Put on the stack' Vector: - When you cannot determine the size - Want to pass data to a function - 'Put on the heap'
Sum up the three different data structures.
Array = fixed size, can only hold a single data type Vector = variable size, can only hold a single data type Class = can hold different data types
Is it easier to pass vectors or arrays to functions?
Vectors as you can pass a vector of any size. With an array you need to specify the size of the array as the argument.
Why would we want to find the index of a certain value in an array?
Arrays can contain a large number of elements.
What is the general form of finding an algorithm (index an array)?
- Create local variable set to -1
- Iterate over each element in array/vector
- If element matches value to look for
(Set local variable to index) - If value is not found then -1 is returned
- Otherwise the index will be the index of the
value
How can you sort an array?
Simply use the std::sort function
e. g.
std: :sort (array.begin(), array.end());
What are array.begin and array.end?
These are called iterators
- They tell the std::sort function what to sort
- By default we want to sort all of the array
- So from the beginning to the end
How can you copy the contents of an array to a vector?
We can again use the begin/end:
std::vector vectorFromArray (array.begin(), array.end());
What can be used to reverse an array?
std::reverse
What can be used to shuffle the contents of an array?
std::shuffle
std::vector is a template class, which means?
It requires you to supply the type of data the vector will
store within the triangle brackets. In this case the vector can only hold ints.
std::vector noteVector;