Vectors

This short program illustrates searching for and erasing an element of a vector.

Notice that we use a template so this will work for any type vector.

The vector class erase method can accept either the starting position of the element to be erased or the start and end points.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<vector>
#include<string>
using namespace std;
template <class T>
int search(T needle, vector<T> haystack) {
   //return the position of first instance of needle in haystack
   int found=-1;
   int pos=0;
   while(pos<haystack.size() && found==-1) {
      if(haystack[pos]==needle) found=pos;
      pos++;
   } //while not found and still more
   return found;
}//search the vector

int main() {
   vector<string> animals; //the vector is empty but we can "push" as many strings as we want
   animals.push_back("cow"); //pushes onto the back, or end, of the vector.
   animals.push_back("horse");
   animals.push_back("cat");
   animals.push_back("mouse");
   animals.push_back("dog");
   animals.push_back("elephant");
   animals.push_back("zebra");
   cout<<"There are "<<animals.size()<<" animals\n";
   for(unsigned v=0;v<animals.size();v++) {
      cout<<animals[v]<<endl;
   }//print each number
   string lookfor="cat";
   int getCat=search(lookfor,animals);
   if(getCat>=0) {
      cout<<"Yes, there is a cat...I'll get rid of it\n";
      animals.erase(animals.begin()+getCat); //get rid of the cat
   }//erase the cat
   cout<<" And now there are:\n";
   for(int v=0;v<animals.size();v++) {
      cout<<animals[v]<<endl;
   }//print each number
   system("pause");
   return 0;
}//main
CODE

NEXT: Read from a file into a vector