Basics of Vectors in C++
A vector is a basically a list or container of any type of a data type you want. If you're making a game it could be good for an inventory type list. But what a vector really is, is a sequential STL (Standard Template Library) container. There are many things you could use vectors for, but I'm going to use it for a list of numbers: 1,2,3, and 4.
Contents [hide]
Declaring Vectors
First of all, make sure you #include . Next declare vector by using the template format:
Simple as that.
Vector Member Functions
Vectors have member functions built in so you can add and delete numbers or strings.
Push Back
Now, we're going to add to our list. To do this use a member function called push_back. Here is how push_back is used:
listnum.push_back(1); //listnum[0]
listnum.push_back(2); //listnum[1]
listnum.push_back(3); //listnum[2]
listnum.push_back(4); //listnum[3]
vector<int> List2(6,440); // SIX elements with value 440
vector<int> List3(List2); // a copy of List2
The list currently looks like this: {4,3,2,1}
Since this is a vector, the first one pushed back will be the last element in the vector. Similar to how a stack works.
Pop Back
The pop_back member function removes the last item added to the vector, then reducing the size by 1.
Clear
The clear member function does exactly what it says, it clears the vector, reducing the size to 0. Therefore, there are no more items in the vector.
We have completely deleted the list.
Size
The size member function can do two things. First it can return the size of the list, or how many items are in your vector. The second case is it can tell you how long a certain item is within your vector.
cout << "this item is " << listnum[3].size() << " characters long."; //only works if vector contains strings
Empty
This member function returns true or false depending on whether of not the vector contains anything; it's a bool type. For example:
cout << "list is empty\n";
} else {
cout << "list is not empty\n";
}
listnum.clear();
if(listnum.empty()) {
cout << "list is empty\n";
} else {
cout << "list is not empty\n";
}
Indexing Vectors
Vectors are automatically indexed, but they start at 0 so listnum[0] is really the first item in the vector. This can be used to change items also, but not delete. Example of changing an item within a vector:
Now, that's assuming we already have a vector with items in it
Insert
This member function inserts a new value into the vector, and in the spot you want it. it works like this:
Here's an example of it actually working, the output should be Hi1 Hi2 HI9 Hi3 Hi4 Hi5.
vectA.push_back("Hi1 ");
vectA.push_back("Hi2 ");
vectA.push_back("Hi3 ");
vectA.push_back("Hi4 ");
vectA.push_back("Hi5 ");
vectA.insert(vectA.begin()+2, "Hi9 ");//inserts hi9 before the 2nd vector item after the beginning vector item
Erase
The erase function can erase a value from the vector. It works like this:
vectA.erase(position);
Here's an example. The output should be Hi1 Hi3 Hi4 Hi5.
vectA.push_back("Hi1 ");
vectA.push_back("Hi2 ");
vectA.push_back("Hi3 ");
vectA.push_back("Hi4 ");
vectA.push_back("Hi5 ");
for(int i = 0; i < vectA.size(); i++){
vectA.push_back("HiNewer");
} // insert 5 more "HiNewer" into the vector
vectA.erase(vectA.begin()+1);//erases the first vector item after the beginning vector item.
Getting all the items in a vector
To do this we use a for loop. This is not a difficult task. We need to find all the arrays in a vector, and print each one as we find it. We do that like this:
vectora.push_back("this ");
vectora.push_back("is ");
vectora.push_back("a ");
vectora.push_back("good ");
vectora.push_back("sentence");
for(int i = 0; i < vectora.size(); ++i){ //declare i to equal 0; while i is
//less than vectora.size (DO CODE); after code add one to i
cout << vectora.at(i); //prints the value of current vector array
}
getchar(); //pauses the app
At
Now, in the code above we see something new. vectora.at(i). This is almost like using vectora[i], except .at has an error return if there is no array at the value you chose. If there is no array at the given value it throws out_of_range exception, while brackets simply just print nothing.
Capacity and Reserve
The member function capacity return the current allocated storage for items in the vector container. Now, the size grows automatically as the vector grows, but you can also edit the capacity with the reserve member function.
vectora.reserve(vectora.capacity()+2); //adds 2 to the storage size of the vector
cout << vectora.capacity(); //displays the storage size of vector again
Please note that to add to the storage size you need to use vectora.capacity()+(whatever you want), or use a number bigger than the current size. Otherwise the size will remain the same.
Swap
Swap simply swaps the first vector with another vector. The format is simply:
// now vectorA has vectorB's values, and vice versa.
Vector example code
Here's a simple example of how vectors and their member functions can be used in a simple inventory application.
#include <string>
#include <vector>
using namespace std;
vector<string> vitems; //this MUST be placed after namespace std!
//declares vitems as a global variable
void dspItems(){
cout << "You currently have:";
if(vitems.empty()) { //if we have no items..
cout << " nothing!";
}
else { // if we do have items
for(int i = 0; i < vitems.size(); ++i){ //declare i to equal 0; while i is
//less than vectora.size (DO CODE); after code add one to i
cout << " " << vitems.at(i) << ","; //prints the value of current vector array
}
}
}
inline void bankrupt(){
cout << "Oh no! Your bag was stolen!\n\n";
vitems.clear(); //deletes all items from vector. vector size is 0
}
inline void insrtItem(int posfrmbegin, string name){
cout << "A/An " << name << " has been randomly thrown in your bag!\n\n";
vitems.insert(vitems.begin() + posfrmbegin, name); //inserts item in selected position
}
inline void rplcItem(int position, string withh){
cout << "You replaced " << vitems.at(position) << " with " << withh << ".\n\n";
vitems.at(position) = withh; //replaces vector item with (withh)
}
inline void dspNum(){
cout << "You currently have: " << vitems.size() << " items.\n\n"; //.size returns number of items
}
inline void addItem(string name){
cout << "You picked up a/an " << name << ".\n\n";
vitems.push_back(name); //adds item to end of vector
}
inline void rmvItem(int position){
cout << "\n\nYou were robbed of your " << vitems.at(position) << ".\n\n";
vitems.erase(vitems.begin() + position); //erases a specific item from vector
}
//***********************************************************
//***********************************************************
int main(int argc, char *argv[])
{
addItem("Potion");//adds potion ***0
getchar();
addItem("Old Boot");//adds old boot ***1
getchar();
addItem("Sword");//adds sword ***2
getchar();
dspNum(); //displays items you have
getchar();
dspItems();
getchar();
rmvItem(1); //removes the first item after the beginning vector item
getchar();
rplcItem(1, "Battle Axe");
getchar();
dspItems();
getchar();
addItem("Rusty Nail");
getchar();
dspItems();
getchar();
bankrupt();
getchar();
dspNum();
getchar();
dspItems();
getchar();
return 0;
}
Marley (not verified)
Yeah I never understood too
Yeah I never understood too much about vectors, and now that you explain it, I'll use it more often.
magnesium (not verified)
Vectors are a kind of
Vectors are a kind of sequence containers. As such, their elements are ordered following a strict linear sequence. Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.
Post new comment