sort an array of objects based on property c++ [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c++ sort with structs
#include <iostream>
using namespace std;
class fish{
private:
int size;
int price;
public:
fish()
{
size=0;
price=0;
}
void set_price(int x)
{
price=x;
}
void set_size(int g)
{
size=g;
}
int get_size()
{
return size;
}
int get_price()
{
return price;
}
void display()
{
cout<<" Fish price is "<<price<<" Fish size is "<<size<<endl;
}
void sort(fish h[5])
{
for (int o=0;o<=5;o++)
{
fish temp;
temp.set_price(0);
if (h[o].get_price()>h[o+1].get_price())
{
temp.get_price()=h[o].get_price();
h[o].get_price()=h[o+1].get_price();
h[o+1].get_price()=temp.get_price();
}
}
}
};
void main()
{
fish a;
fish b[5];
a.set_size(500);
a.set_price(2);
a.display();
for (int i=0;i<=5;i++)
{
b[i].set_size(i*2);
b[i].set_price(i*100);
}
for (i=0;i<=5;i++)
b[i].display();
}
I want to to find out how I send array b, and sorting it. Also I was going to ask about the destructors and where I can put them into my code.

To swap fish around when you are sorting you should write this
fish tmp = h[o];
h[o] = h[o+1];
h[o+1] = tmp;
You are sorting based on the fish price, but it's the whole fish that should be sorted.
On your other question, there is no need for destructor in this code. Your fish class doesn't need to do any 'clean up' so it doesn't need a destructor.

if you're looking to sort your array by a given element the STL container should be just fine, if not i would use this method
template<class T>
void quickSort(T * elements, unsigned int first, unsigned int last)
{
if(first < last) //make sure params are in bounds
{
T t = elements[first]; //t is PIVOT
unsigned lastLow = first; //create last low item
unsigned i; //used for loop/swapping
for(i = first + 1; i <= last; i++) //run through entire bounds
if(elements[i] < t) //if elements is less than Low
{
<< " adding one onto lastLow...\n";
lastLow++; //move lastLow up one
swap(elements,lastLow, i); //swap lastlow and i
}
swap(elements,first, lastLow); //swap first and lastlow
if(lastLow != first) //if lastlow is not first element
quickSort(elements, first, lastLow - 1);
if(lastLow != last) //if lastlow is not last element
quickSort(elements, lastLow + 1, last);
}
}
this is a common quicksort function used to sort an array. Just replace the right variables to represent your data E.g. T * elements becomes Fish * stuff, T t = Elements[first] becomes double price = stuff[first] and so on.

Related

Permutations of String Using Stack C++

The program I have below finds all the permutations of a given string using a stack without recursion. I am having some trouble understanding what the place in the struct is for and how it plays into the logic for the algorithm. Could anyone help me understand this code? I have a struct that only has two entities:
class Node
{
public:
string word; // stores the word in the node
Node *next;
};
I would just like to understand why the place entity is needed.
Here is the code that finds all the permutations of a given string:
struct State
{
State (std::string topermute_, int place_, int nextchar_, State* next_ = 0)
: topermute (topermute_)
, place (place_)
, nextchar (nextchar_)
, next (next_)
{
}
std::string topermute;
int place;
int nextchar;
State* next;
};
std::string swtch (std::string topermute, int x, int y)
{
std::string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute (std::string topermute, int place = 0)
{
// Linked list stack.
State* top = new State (topermute, place, place);
while (top != 0)
{
State* pop = top;
top = pop->next;
if (pop->place == pop->topermute.length () - 1)
{
std::cout << pop->topermute << std::endl;
}
for (int i = pop->place; i < pop->topermute.length (); ++i)
{
top = new State (swtch (pop->topermute, pop->place, i), pop->place + 1, i, top);
}
delete pop;
}
}
int main (int argc, char* argv[])
{
if (argc!=2)
{
std::cout<<"Proper input is 'permute string'";
return 1;
}
else
{
permute (argv[1]);
}
return 0;
}
Place helps you to know where is going to be the next character "swap". As you can see, it increments inside the for loop. As you can see, inside that for loop, it behaves like a pivot and i increments in order to behave like a permutator (by swapping characters)

Seg. fault resizing array C++

I have a priority queue array that is filled with "Jobs" (name + priority). I've been able to get everything queue related working aside from re sizing if it is full. Here is the bits that I think are causing a segmentation fault that I haven't been able to figure out.
EDIT:
Here is a bit more code that will compile, I left in the rest of the functions in case those might help in any way. Right now the initial capacity is set to 5, when you try to add a job to the full list it will double the capacity of the array and allow you to add a couple more jobs before a SEG. fault.
pq.h
#ifndef PQ_H
#define PQ_H
#include "interface.h"
#include <string>
using namespace std;
class Job {
public:
int getPriority();
string getTaskName();
void setPriority(int val);
void setTaskName(string tname);
Job();
private:
int priority;
string taskName;
};
class PriorityQueue {
public:
PriorityQueue();
~PriorityQueue();
int size();
bool isEmpty();
void clear();
void enqueue(string value, int priority);
string dequeue();
string peek();
int peekPriority();
PriorityQueue(const PriorityQueue & src);
PriorityQueue & operator=(const PriorityQueue & src);
private:
static const int INITIAL_CAPACITY = 5;
Job *array;
int count;
int capacity;
void expandCapacity() {
Job *oldArray = array;
capacity *= 2;
array = new Job[capacity];
for (int i = 0; i < count; i++) {
array[i] = oldArray[i];
}
delete[] oldArray;
}
};
#endif
pq.cpp
#include <iostream>
#include <cstring>
using namespace std;
//#include "job.h"
#include "pq.h"
Job::Job() // Constructor
{
priority= 0;
taskName = "There are no items in the list.";
}
int Job::getPriority(){ // returns the prority of the job
return priority;
}
string Job::getTaskName(){ // returns the name of the job
return taskName;
}
void Job::setPriority(int val){ // sets the priority of a newly created job
priority = val;
}
void Job::setTaskName(string tname){ // sets the name of a new job
taskName = tname;
}
PriorityQueue::PriorityQueue() // constructor
{
count = 0;
capacity = INITIAL_CAPACITY - 1;
array = new Job[INITIAL_CAPACITY];
}
PriorityQueue::~PriorityQueue() { // destructor
delete [] array;
}
int PriorityQueue::size() { // returns the number of jobs in the queue
return count;
}
bool PriorityQueue::isEmpty() { // returns true if queue is empty
if (count != 0){
return false;
}else{
return true;
}
}
void PriorityQueue::clear() { // clears queue of all jobs
count = 0;
// need to make it remove and delete the items
}
void PriorityQueue::enqueue(string value, int priority) {
// tests size to see if Queue is a max capacity
if(count == capacity){
expandCapacity();
cout << "\tList was full and has been expanded\n";
}
array[++count].setPriority(priority);
array[count].setTaskName(value);
// upheap operations
Job v = array[count];
int tempcount = count;
while (array[tempcount/2].getPriority() >= v.getPriority()){
array[tempcount] = array[tempcount/2];
tempcount = tempcount/2;
array[tempcount] = v;
}
}
string PriorityQueue::dequeue() {
// removes the job with the highest priority from the queue and returns the name
if(this->isEmpty()){ // make sure the queue isnt empty
string empty = "The queue is empty";
return empty;
}else{
Job remove = array[1];
array[1] = array[count--];
int j;
Job v;
int k = 1;
v = array[k];
while(k <= count/2){
cout << "dequeuewhile"; // test
j = k + k;
if(j < count && array[j].getPriority() > array[j+1].getPriority()){
j++;
cout << "dequeueloop if1"; // test
}
if(v.getPriority() <= array[j].getPriority()){
cout << "dequeueloop if2"; //test
break;
}
array[k] = array[j];
k = j;
}
array[k] = v;
return remove.getTaskName(); // returns the name of the removed job
}
}
string PriorityQueue::peek() { // returns the name of the highest priority job without removing it from the queue
if(count == 0){
return array[0].getTaskName();
}
return array[1].getTaskName();
}
int PriorityQueue::peekPriority() { // returns the priority from the highest priority job without removing it from the queue
if(count == 0){
cout << "\tThere are no items in the list.\n";
return array[0].getPriority();
}
return array[1].getPriority();
}
I think that when you do ++count, the next use of count will be out of bounds for the array.
array[++count].setPriority(priority);
// SEGMENTATION FAULT HERE
array[count].setTaskName(value);
If the capacity of the array is 5, and count was 4, then you just incremented count to 5, and tried to access element 5, which is out-of-bounds.
array = new Job[capacity];
for (int i = 0; i < count; i++) {
array[i] = oldArray[i];
}
Lets assume capacity is 10, so you've got an array of 10 elements, ranging from elements 0 to 9.
counttells us how many elements are being used.
If count happens to be 9, then when you increment count by one, it is now 10. Then, when line come you marked as producing segment fault comes, you're trying to access element 10, in our example. There is no element 10in an array of length 10, so you're out of bounds.
array[++count].setPriority(priority); // array[10], but last element is 9!
// SEGMENTATION FAULT HERE
array[count].setTaskName(value); // array[10], but last element is 9!
And, of course, everything after that part causes the same issue, as you keep using array[count].
Your original code did exactly as the previous answer given by #antiHUMAN.
The problem you're having is mixing or erroneously using 0-based and 1-based concepts.
Your first mistake is to make capacity a 0-based number. The capacity should denote the maximum number of items in an array, thus you should not be subtracting 1 from it. If the array can hold 5 items, then capacity should be 5, not 4.
PriorityQueue::PriorityQueue() // constructor
{
count = 0;
capacity = INITIAL_CAPACITY; // this remains 1-based.
array = new Job[INITIAL_CAPACITY];
}
or using the initializer-list:
PriorityQueue::PriorityQueue() : count(0),
capacity(INITIAL_CAPACITY),
array(new Job[INITIAL_CAPACITY]) {}
The 0-based number in your situation should be count, not capacity. Given that, since count is 0-based, and capacity is 1-based, your test in enqueue needs to be changed:
if(count + 1 == capacity){
expandCapacity();
cout << "\tList was full and has been expanded\n";
}
Note that 1 is added to count to account for the fact that count is 0-based and capacity is 1 based.

Sorted list: must have class/struct/union

so i have been working on a code for over two weeks and its not going too well. here are the instructions and the code is below it, as well as errors:
Task 1: Create one instance of this class. (the sorted list; he also had other instructions on HOW to start the code, but its already been done by me below in the code such as typedef...) You also need to read in data from one data file: float.dat, which contains the following numbers:
5.5
6.2
7.1
8.0
9.0
10.0
1.0
2.0
3.3
4.4
Data in float.dat contains floating numbers, which should be inserted into the object of SortedList. Note that you do not have any prior knowledge about data values in float.dat, but we assume that there are 10 elements in the data file.
Task 2: Use GetNextItem( ) to print out all the elements in the list in sorted sequence on computer screen.
Task 3: Use GetNextItem( ) to output all the elements in the list in sorted sequence onto a data file, output.dat.
Task 4: Design your test cases to demonstrate InsertItem( ), DeleteItem( ) and RetrieveItem( ) are working as expected.
here is the code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define MAX_ITEMS 10
typedef float ItemType;
class SortedList
{
private:
int length;
ItemType values[MAX_ITEMS];
int currentPos;
enum RelationType { LESS, GREATER, EQUAL };
public:
SortedList() {length = 0; currentPos = -1;}
int getLength() {return length;}
RelationType ComparedTo(ItemType x)
{
if (length > x.getLength())
return LESS;
else if (length == x.getLength())
return GREATER;
else
return EQUAL;
}
void MakeEmpty() {length = 0;}
void InsertItem(ItemType x)
{
int first = 0, last = length --;
bool moreToSearch = (first <= last);
int location = 0;
int midpoint= (first + last) / 2;
while (moreToSearch)
{
switch (x.ComparedTo(values[location]))
{
case LESS: //search in 1st half
moreToSearch = (first <= last);
break;
case GREATER:
location++;
moreToSearch = (location < length);
break;
}
}
for (int index = length; length > location; index--)
{
values[index] = values[index - 1];
}
values[location] = x;
length++;
}
void DeleteItem(ItemType x)
{
int location = 0;
while (x.ComparedTo(values[location]) != EQUAL)
location++;
for (int index = location ++; index < length; index++)
values[index --] = values[index];
length--;
}
void RetrieveItem(ItemType &x, bool & found)
{
int midpoint;
int first = 0, last = length - 1;
bool moreToSearch = (first <= last);
found = false;
int index = 0;
while (moreToSearch && !found)
{
midpoint = (first + last) / 2;
switch (x.ComparedTo(values[index++]))
{
case LESS: //search in 1st half
moreToSearch = (first <= last);
last = midpoint - 1;
break;
case GREATER: //Search in 2nd half
first = midpoint + 1;
moreToSearch = (first <= last);
break;
case EQUAL: //x has been found
found = true;
break;
}
}
}
int LengthIs() {return length;}
void ResetList() {currentPos = -1;}
bool IsFull()
{
if (length < 9)
return false;
else
return true;
}
void GetNextItem(ItemType &x)
{
currentPos++;
x = values[currentPos];
cout << x;
}
};
int main()
{
SortedList x;
ifstream inFile; ofstream output;
string line;
bool allAboutLists;
int i = 0;
int size = 0;
inFile.open("float.txt");
float values[10];
while (!inFile.eof()) // write or read data from inFile into values
{
inFile >> values[i];
i++;
size++; // this will count how many values there are in the array
x.InsertItem(values[i]);
++i;
}
x.ResetList();
cout << "The following is the list that's been made:" << endl << endl;
x.InsertItem(64);
//x.printlist();
cout << endl;
x.DeleteItem(64);
//x.printlist();
x.RetrieveItem(7.1, allAboutLists);
cout << endl;
cout << endl << "The length is: "; x.LengthIs(); cout << endl;
cout << "Is the list full?: " << boolalpha << x.IsFull() << endl;
cout << "The next item is: ";
for (int i = 0; i < 10; i++)
{
cout << x.GetNextItem << endl;
}
x.ResetList();
inFile.close();
output.open("output.txt");
for (int f = 0; f < 10; f++)
{
output << x.GetNextItem << endl;
}
system("pause");
return 0;
}
and the compiler keeps saying this:
(25) error C2228: left of '.getLength' must have class/struct/union [they mean the x. its red lined under, same for the rest of those left of etc..]
(27) error C2228: left of '.getLength' must have class/struct/union
(44) error C2228: left of '.ComparedTo' must have class/struct/union
(66): error C2228: left of '.ComparedTo' must have class/struct/union
-and also, 7.1 in main has something about refernce type mistake.
I am in extereme hurry as i have been working on it for 2 weeks now and its driving me crazy ! I have the code done as seen and more than wnough and just need to know what to change exactly because I am following everything I have been searching and researching yet its no good. so precise details or code specifically taken from mine and fixed would be appreciated.
Thanks!
You are passing x as ItemType which is a float.
float doesn't have those methods... looks like you wanted to pass it as a SortedList
The compare function needs two parameters in order to do a compare. Instead of ComparedTo, you may want to call it CompareToLocation.
RelationType CompareToLocation(ItemType x, size_t location){
if(x < values[location]) return LESS;
if(x == values[location]) return EQUAL;
return GREATER;}
An example usage would be:
result = CompareToLocation(x, location);
// ...
You defined ComparedTo as a method for SortedList, yet everytime you call that function, you call it on ItemType objects, which are actually floats.
As you can see in the definition of the method, you are trying to use, once again, SortedList methods on float Objects:
RelationType ComparedTo(ItemType x)
{
if (length > x.getLength())
return LESS;
else if (length == x.getLength())
return GREATER;
else
return EQUAL;
}
Your problem is not really a compiling one, but a conceptual one, since you don't seem to grasp what your are actually coding.
I'd recommend have your declarations and implementations separate, so you can see at a glance how does your class work.
Your class declaration should look something like this:
class SortedList
{
private:
int length;
ItemType values[MAX_ITEMS];
int currentPos;
enum RelationType { LESS, GREATER, EQUAL };
public:
SortedList();
int getLength();
RelationType ComparedTo(ItemType x) ;
void MakeEmpty();
void InsertItem(ItemType x) ;
void DeleteItem(ItemType x);
void RetrieveItem(ItemType &x, bool & found);
int LengthIs();
void ResetList();
bool IsFull();
void GetNextItem(ItemType &x);
};
You should focus on each method, making clear what each one of them is trying to achieve, and what does it need to achieve it (parameters).
For example:
RelationType ComparedTo(ItemType x) ;
Your SortedList class has this function, which receives an ItemType (float) as a parameter.
What is this trying to achieve? How do you compare a whole ordered list to a single element?
How can a single number be greater, less or EQUAL to a set of numbers?
Maybe what you really want to do is compate parameter X with an element inside the list?
If this is the case, how do you know which element in the list must be compared to parameter X? You should add another parameter telling you which element inside your ordered list to compare X to.
I quess this doesn't really solve your problem, but at least I hope this helps you understand better what your problem is.

Implementing min function

Good day, I found this priority queue implementation and I am trying to get a min version of it (instead of max). I have no idea where to start. I tried mixing the signs of the functions (naive attempt) but it didn't get me far. Any help of how to implement it and a few words explaining it are very wellcome. The source is below:
Note I have left it's comments
#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;
class PriorityQueue
{
vector<int> pq_keys;
void shiftRight(int low, int high);
void shiftLeft(int low, int high);
void buildHeap();
public:
PriorityQueue(){}
PriorityQueue(vector<int>& items)
{
pq_keys = items;
buildHeap();
}
/*Insert a new item into the priority queue*/
void enqueue(int item);
/*Get the maximum element from the priority queue*/
int dequeue();
/*Just for testing*/
void print();
};
void PriorityQueue::enqueue(int item)
{
pq_keys.push_back(item);
shiftLeft(0, pq_keys.size() - 1);
return;
}
int PriorityQueue::dequeue()
{
assert(pq_keys.size() != 0);
int last = pq_keys.size() - 1;
int tmp = pq_keys[0];
pq_keys[0] = pq_keys[last];
pq_keys[last] = tmp;
pq_keys.pop_back();
shiftRight(0, last-1);
return tmp;
}
void PriorityQueue::print()
{
int size = pq_keys.size();
for (int i = 0; i < size; ++i)
cout << pq_keys[i] << " ";
cout << endl;
}
void PriorityQueue::shiftLeft(int low, int high)
{
int childIdx = high;
while (childIdx > low)
{
int parentIdx = (childIdx-1)/2;
/*if child is bigger than parent we need to swap*/
if (pq_keys[childIdx] > pq_keys[parentIdx])
{
int tmp = pq_keys[childIdx];
pq_keys[childIdx] = pq_keys[parentIdx];
pq_keys[parentIdx] = tmp;
/*Make parent index the child and shift towards left*/
childIdx = parentIdx;
}
else
{
break;
}
}
return;
}
void PriorityQueue::shiftRight(int low, int high)
{
int root = low;
while ((root*2)+1 <= high)
{
int leftChild = (root * 2) + 1;
int rightChild = leftChild + 1;
int swapIdx = root;
/*Check if root is less than left child*/
if (pq_keys[swapIdx] < pq_keys[leftChild])
{
swapIdx = leftChild;
}
/*If right child exists check if it is less than current root*/
if ((rightChild <= high) && (pq_keys[swapIdx] < pq_keys[rightChild]))
{
swapIdx = rightChild;
}
/*Make the biggest element of root, left and right child the root*/
if (swapIdx != root)
{
int tmp = pq_keys[root];
pq_keys[root] = pq_keys[swapIdx];
pq_keys[swapIdx] = tmp;
/*Keep shifting right and ensure that swapIdx satisfies
heap property aka left and right child of it is smaller than
itself*/
root = swapIdx;
}
else
{
break;
}
}
return;
}
void PriorityQueue::buildHeap()
{
/*Start with middle element. Middle element is chosen in
such a way that the last element of array is either its
left child or right child*/
int size = pq_keys.size();
int midIdx = (size -2)/2;
while (midIdx >= 0)
{
shiftRight(midIdx, size-1);
--midIdx;
}
return;
}
int main()
{
//example usage
PriorityQueue asd;
asd.enqueue(2);
asd.enqueue(3);
asd.enqueue(4);
asd.enqueue(7);
asd.enqueue(5);
asd.print();
cout<< asd.dequeue() << endl;
asd.print();
return 0;
}
Well generally in such problems, i.e. algorithms based on comparison of elements, you can redefine what does (a < b) mean. (That is how things in standard library work by the way. You can define your own comparator.)
So if you change it's meaning to the opposite. You will reverse the ordering.
You need to identify every comparison of elements, and switch it. So for every piece of code like this
/*if child is bigger than parent we need to swap*/
if (pq_keys[childIdx] > pq_keys[parentIdx])
invert it's meaning/logic.
Simple negation should do the trick:
/*if child is NOT bigger than parent we need to swap*/
if !(pq_keys[childIdx] > pq_keys[parentIdx])
You do not even need to understand algorithm. Just inverse meaning of what lesser element is.
Edit:
Additional note. You could actually refactor it into some kind of bool compare(T a, T b). And use this function where comparison is used. So whenever you want to change the behaviour you just need to change one place and it will be consistent. But that is mostly to avoid work to look for every such occurrence, and stupid bugs and when you miss one.
Easier:
std::prioroty_queue<int, std::vector<int>, std::greater<int>> my_queue;
If this is part of an exercise, then I suggest following the standard library's design principles: split the problem up:
data storage (e.g. std::vector)
sorting or "heapifying" algorithm (c.f. std::make_heap etc.)
ordering criteria (to be used by 2. above)
Your class should give you some leeway to change any of these independently. With that in place, you can trivially change the "less-than" ordering for a "greater than" one.

Hash Table of Vectors of Person Objects c

I've been working on a very in depth project for one of my classes. It supposed to read in Person objects and put them into a hash table. I'm still trying to get my head around the concept of a hash table so any help would be appreciated.
It will be hashing based on last name and since some people may have the same last name, I was going to make each bucket a vector of Person objects. I'm trying to test the class by adding a person to the hash function and then returning it. My code compiles successfully but I get a thread error in the put function on this line: table[index].push_back(p);
Could anyone please help me figure out what is going wrong? Thank you!
int main()
{
HashTable ht(10);
ht.put(p1, p1->lName);
ht.getName("Booras");
}
HashTable:
#include "Person.h"
#include <vector>
class HashTable: public DataStructures
{
private:
vector<vector<Person>> table;
public:
HashTable(int tableSize);
~HashTable();
int tableSize;
void getName(string str); //prints out friends with matching name
void put(Person p, string str);
void remove(Person *p, string str);
int hash(string str);
};
HashTable::HashTable(int tableSize)
{
vector< vector<Person> > table(tableSize, vector<Person>(tableSize));
for (int i = 0; i < tableSize; i++) {
table.push_back(vector<Person>()); // Add an empty row
}
}
HashTable::~HashTable()
{
}
//Find a person with the given last name
void HashTable::getName(string key)
{
int index = hash(key);
for(int i=0; i<table[index].size(); i++)
{
if(table[index][i].lName.compare(key) == 0)
std::cout << "Bucket: " << index << "Bin: " << i;
table[index][i].print();
}
//create exception for person not found
}
void HashTable::put(Person p, string str)
{
int index = hash(str);
table[index].push_back(p);
}
void HashTable::remove(Person *p, string str)
{
int index = hash(str);
int i=0;
while(&table[index][i] != p && i<table[index].size())
i++;
for(int j=i; j<table[index].size()-1; j++)
table[index][j] = table[index][j+1];
table[index].pop_back();
}
int HashTable::hash(string str)
{
int hashValue = 0;
for(int i=0; i<str.length(); i++)
{
hashValue = hashValue + int(str[i]);
}
hashValue %= tableSize;
if(hashValue<0) hashValue += tableSize;
return hashValue;
}
Main:
int main() {
Person *p1 = new Person("Kristy", "Booras", "Reston", "03/15");
HashTable ht(10);
ht.put(*p1, p1->lName);
ht.get("Booras");
return 0;
}
You don't show us the HashTable::hash(string) member function, but I'd assume that your problems originate in the HashTableconstructor: You don't initialize the tableSize member variable, which you'll need to calculate a valid hashed index.
While looking at the constructor:
HashTable::HashTable(int tableSize)
{
vector< vector<Person> > table(tableSize, vector<Person>(tableSize));
This has initialized table to have tableSize non-empty elements, for a total of tableSize * tableSizedefault-constructed Person objects.
for (int i = 0; i < tableSize; i++) {
table.push_back(vector<Person>()); // Add an empty row
}
}
Now you have added more rows, so that table.size() == 2*tableSize, with the first half of entries non-empty (as explained above) and the second half holding empty vectors.
That is probably not what you intended.
And in all of that you haven't initialized the member tableSize. It easily gets confusing, if you use local variables or argument names that hide member names.