Finding a Value (find.cpp)
Suppose you want to find the first salary > $50,000 in a vector of salary values. We can simply inspect each element until we find a match or reach the end of the vector:
#include <iostream>
#include <vector>
using namespace std;
int
find_first_greater(vector<double> a , double t)
{ int i = 0;
while (i < a.size())
{ if (a[i] > t)
return i;
else
i++;
}
return -1;
}
int main()
{ vector <double> salaries(5);
salaries[0] = 35000.0;
salaries[1]
= 65000.0;
salaries[2]
= 48000.0;
salaries[3]
= 78000.0;
salaries[4]
= 51500.0;
int
i = find_first_greater(salaries, 50000);
if
(i >0)
{ cout << “The first salary above 50000
is at index “ << i
<< “ and is “ << salaries[i]
<< endl;
}
return
0;
}
Counting (Program count.cpp)
Suppose we want to find how many salaries are > $50,000
#include <iostream>
#include <vector>
using namespace std;
int
count_greater(vector<double> a , double t)
{ int count = 0;
int i;
for (i = 0; i < a.size(); i++)
{ if (a[i] > t)
count++;
return count;
}
int main()
{ vector <double> salaries(5);
salaries[0] = 35000.0;
salaries[1]
= 65000.0;
salaries[2]
= 48000.0;
salaries[3]
= 78000.0;
salaries[4]
= 51500.0;
int
count = count_greater(salaries, 50000);
cout
<< count << “ salary above 50000 << endl;
}
return
0;
}
Removing Elements (Remove.cpp)
Suppose we want to remove an element from a vector. If the elements in the vector are not in any particular order, that task is easy to accomplish. Simply overwrite the element to be removed with the last element of the vector, then shrink the size of the vector.
#include <iostream>
#include <vector>
#include <string.
using namespace std;
void erase
(vector<string> &a , int pos)
{ int last_pos = a.size() – 1;
a[pos] = a[last_pos];
a.pop_back();
}
void print (vector
<string> a)
{ int i;
for (i = 0; i < a.size(); i++)
cout << “[“ << i << “]” <<
a[i] << endl;
}
int main()
{ vector <string> staff(5);
staff[0] = “Hacker, Harry”;
staff[1]
= “Reindeer, Rodolf”;
staff[2]
= “Cracker Carl”;
staff[3]
= “Lam Larry”;
staff[4]
= “Sandman, Susan”;
print(staff);
int
pos; cout << “Remove which
element?”;
cin
pos;
erase(staff,
pos);
print
(staff);
return
0;
}
Inserting Elements (Insert.cpp)
Suppose we want to insert a new element into a vector:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void insert
(vector<string> &a , int pos,
string s)
{ int last = a.size() – 1;
a.push_back(a[last]);
int i;
for (i = last; i > pos; i--)
a[i] = a[i - 1];
a[pos] = s;
}
void print (vector
<string> a)
{ int i;
for (i = 0; i < a.size(); i++)
cout << “[“ << i << “]” <<
a[i] << endl;
}
int main()
{ vector <string> staff(5);
staff[0] = “Cracker Carl”;
staff[1]
= “Hacker, Harry ”;
staff[2]
= “Lam Larry”;
staff[3]
= “Reindeer, Rudolf”;
staff[4]
= “Sandman, Susan”;
print(staff);
int
pos; cout << “Insert before which
element?”;
cin
>> pos; insert(staff, pos, “New,
Nina”);
print
(staff);
return
0;
}