Vectors

This program reads a file into a vector, and then sorted.

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
43
44
45
46
47
48
49
50
51
52
53
//Read in name and year born from a file into a vector
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
const int currentYear=2016;
void getFile(vector<string> &names,vector<int> &yearBorn) {
  string input,yearString;
  ifstream people("c:/mycpp/names2.txt"); //input file stream
  if(people) { //file was opened
    while(getline(people,input)) { //Example: input="Jay 1994" 
      int p=input.find_first_of(","); //Example: p=3 
      if(p>=0) {
        names.push_back(input.substr(0,p)); //Example: name="Jay"
        yearString=input.substr(p+1); // Example: yearString="1994"
        yearBorn.push_back(stoi(yearString)); //stoi=String To Int, Example yearBorn=1994
      }//there was a comma
    }//each line
    people.close(); 
  }
}//getFile
void sort(vector<string> &names,vector<int> &yearBorn) {
  int size=names.size();
  for(int i=0;i<size;i++) {
    for(int j=0; j<i;j++) {
      if(names[j]>names[j+1]) {
        //swap doesn't work with vectors, include algorithm and use iter_swap
        iter_swap(names.begin() + j, names.begin() +(j+1) );
        iter_swap(yearBorn.begin() + j, yearBorn.begin() +(j+1) );
      } //out of order
    } //inner loop
  }//outer loop
 }//sort
void showAll(vector<string> names,vector<int> yearBorn) {
  cout<<"NAME\tAGE\n";
  int count=names.size();
  for(int i=0;i<count;i++) {
    int age=currentYear-yearBorn[i];
    cout<<names[i]<<"\t"<<age<<endl;
  }//for
}//showAll

int main(void) {
  vector<string> names;
  vector<int> yearBorn;
  getFile(names,yearBorn);
  sort(names,yearBorn);
  showAll(names,yearBorn);
  system("pause");
  return 0;
} //main 
CODE

The input file has a name and the year born for each person separated by a comma, with one person on each line.

NEXT: Searching an Array