Array, Vector, etc...

Hi,

I need help creating a table. It can be a vector, 2d array, or 4 parallel arrays. I need the number of rows to be a variable and the number of columns to be 4. It needs to be in a class. The information stored will be added later. I need to be able to sort by the information in the second column.

Help please??
Start by defining a structure representing the data in a single row. Then define a function that compares two rows by last name. For example:

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
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>

struct person { std::string first_name, last_name; }; 

std::string to_string(person const& p)
{ return p.last_name + ", " + p.first_name; }

// return true if person a appears before person b in order.
bool collate_by_last_name(person a, person b)
{ return a.last_name < b.last_name; } 

void print_people(std::vector<person> const& people)
{ 
  for (auto const& p: people)
    std::cout << to_string(p) << '\n';
  std::cout << '\n';
}

int main()
{
  std::vector<person> account_holders;
  
  person a{ "John", "Smith" };
  person b{ "Jane", "Doe"   }; 
  person c{ "Joe",  "Blow"  };
  
  account_holders.push_back(a);
  account_holders.push_back(b);
  account_holders.push_back(c); 
  
  print_people(account_holders);
  
  std::sort(account_holders.begin(), account_holders.end(), 
            collate_by_last_name);
            
  print_people(account_holders);
}
Last edited on
Topic archived. No new replies allowed.