How to Create a Vector List
A vector is a re-sizable container used to store data sequentially in a computer program. Vectors are similar to arrays, which are also containers used to store data, and which exist in many different computer programming languages. However, vectors have some benefits over other storage objects that include deques and lists. Because the C programming language has been around so long and has been used for many complex numerical calculations, this article will discuss creating a vector in C.
Instructions
-
-
1
Include the vector class in your program by coding "#include <vector>."
-
2
Define the vector with a valid data type, such as Integer, Boolean or String. Give the vector a name so it can be accessed in the code.
-
-
3
Add values to the vector by coding "push_back." This function puts a value at the end of the vector array. For example, "myVector.push_back(22)" puts the number 22 in the array. Coding "myVector.push_back(32)" next creates an array with the value 22 followed by 32.
-
4
Retrieve values from the vector in linear or random order. To do so in order, declare a variable to be a counter that begins at zero. Loop through the array counting from zero to "myVector.size()." Access the individual values with "myVector[x]" where x is the current index of the vector array.
-
5
Manipulate the contents of the vector if necessary. Remove the last element using the "pop_back" function. "Clear" sets the count to zero by removing every value; "erase" will remove specific values individually.
-
1
Tips & Warnings
Inserting or removing elements from the middle of a vector is more time consuming than doing so with deques or lists.
Vectors have more storage allocated than other arrays because vectors can be re-sized automatically.
References
- Photo Credit Hemera Technologies/PhotoObjects.net/Getty Images