Accessing element of an array of struct. - c++

So I have an struct
struct car{
string ownerName;
float price;
int year;
};
and I declared an array of these structs
car *cars = new car[1000]
Each car has an index, for example, the car with index 0 has name John Smith.
So, my question is knowing the name of the owner how do I access the index of the car. I know that the other way i would write
cars[0].name,
to get the name, but how would i do it backwards?

Two possible ways come to my mind.
One is writing a function that finds index by name.
#include <string>
using namespace std;
car *find_by_name(car* cars, const string& name, int from, int to) {
car* car_ptr = NULL;
for(int i = from; i < to; i++) {
if (cars[i].ownerName == name) {
car_ptr = cars+i;
break;
}
}
return car_ptr;
}
As you may notice, this function is very expensive (O(n)).
The other one and the easiest one, in my opinion, is using Map or HashMap to do so.
#include <map>
#include <string>
#include <iostream>
using namespace std;
car set_new_val(map<string, car*>& my_map, const string& name, const float price, const int year) {
car* car_heap = new car();
car_heap->ownerName = name;
car_heap->price = price;
car_hep->year = year;
my_map.insert(pair<string, car*>(name, car_heap));
}
car* find_car_by_name(const map<string, car*>& my_map, const string& name) {
map<string, car*>::iterator it;
if ((it = my_map.find(name)) == my_map.end())
return NULL;
return it->second;
}
int main(int argc, char* argv[]) {
map<string, car*> my_cars_data;
set_new_val(my_cars_data, "James", 2233000.5, 2013);
set_new_val(my_cars_data, "Dave", 1222000.5, 2011);
set_new_val(my_cars_data, "Aaron", 1222000.75, 2012);
car* james_car = find_car_by_name(my_cars_data, "James");
cout << "Year " << james_car->year << endl;
car* null_car = find_car_by_name(my_cars_data, "Santa");
if (null_car == NULL)
cout << "No owner with the name Santa is recorded" << endl;
...
...
free_map(my_map);
return 0;
According to C++11, lookup for a key using Map takes O(lgn) (HashMap is O(1)), for more details read here . That's a big pro, if you handle mass of data (not to mention that it is easier to maintain).

If you use a sequential container (array, vector...) you have to search for the name. In an unsorted array a linear search is required.
// linear search
string name = "joe";
auto it = find_if(begin(cars), end(cars),
[&name](const car& c) { return c.ownerName == name; });
auto index = it - begin(cars);
If you have performance problems with this approach you could sort the array and use a binary search (preferable if your array of cars does not change) or use a associative container which gives you fast access to an element by key (map, multi_map, unordered_map...)
// binary search
struct {
bool operator()(const car& lh, const car& rh) { return lh.ownerName < rh.ownerName; };
bool operator()(const car& lh, const std::string& rh) { return lh.ownerName < rh; };
bool operator()(const std::string& lh, const car& rh) { return lh < rh.ownerName; };
} byName;
sort(begin(cars), end(cars), byName);
auto it2 = lower_bound(begin(cars), end(cars), name, byName);
if (it != end(cars) && it->ownerName == name)
{
auto index2 = it - begin(cars);
}

Related

Sorting a vector with pointer at object C++

If anyone can help I would be very grateful.
How do i sort this vector:
vector<Person*>person
by this criterium:
Surname
I have already tried it using set but it removes object if there is more than 2 objects with same Surname
there are lot of string variables, and I need to sort it by
Surname
and then if surnames are the same, then I need to sort them by
Name
and also it sorts by hexadecimal value of that pointer...
EDIT:
More code as you ask:
for (pChild = pRoot->FirstChildElement("Member"); pChild != NULL; pChild = pChild->NextSiblingElement())
{
string Surname = pChild->Attribute("surname");
string Name = pChild->Attribute("name");
string DateOfBirth = pChild->Attribute("dateofbirth");
person.push_back(new Person(Surname, Name, DateOfBirth));
}
Without you showing more of your code, it is hard to help you, but I would look at the documentation for std::sort() as you can create custom operators to sort your vector.
Here's a complete example
#include <vector>
#include <iostream>
#include <algorithm>
class Person
{
public:
std::string s1, s2, s3;
Person(std::string S1, std::string S2, std::string S3) : s1(S1), s2(S2), s3(S3) {}
};
struct less_than_key
{
inline bool operator() (const Person* const p1, const Person* const p2)
{
if (p1->s1 < p2->s1)
return true;
else if (p1->s1 == p2->s1 && p1->s2 < p2->s2)
return true;
return false;
}
};
int main()
{
std::vector<Person*> persons{ new Person("C", "D", "E"), new Person("C", "C", "D"),
new Person("B", "C", "D"), new Person("B", "C", "E")};
std::sort(persons.begin(), persons.end(), less_than_key());
for (auto person : persons)
{
std::cout << person->s1 << ' ' << person->s2 << std::endl;
}
return 0;
}
I had a bit of fun doing it with std::set. There are a couple of examples of comparators. One function and one "functor."
#include <iostream>
#include <set>
#include <string>
struct Person {
uint64_t id;
std::string name;
std::string family_name;
bool operator<(const Person &other) const {
if (family_name == other.family_name) {
if (name == other.name) {
return id < other.id;
} else {
return name < other.name;
}
} else {
return family_name < other.family_name;
}
}
};
std::ostream &operator<<(std::ostream &os, const Person &x) {
return os << '{' << x.id << ", " << x.name << ", " << x.family_name << '}';
}
bool person_ptr_less(const Person *a, const Person *b) { return *a < *b; }
class PersonPtrComparator {
public:
bool operator()(const Person *a, const Person *b) const { return *a < *b; }
};
int main() {
std::set<Person *, bool (*)(const Person *, const Person *)> people(
person_ptr_less);
people.emplace(new Person{1, "Joe", "Smith"});
people.emplace(new Person{2, "Joe", "Blow"});
people.emplace(new Person{3, "Joa", "Smith"});
people.emplace(new Person{4, "Joe", "Smith"});
std::set<Person *, PersonPtrComparator> people_2(people.begin(),
people.end());
for (const auto &x : people) {
std::cout << *x << '\n';
}
std::cout << "---\n";
for (const auto &x : people_2) {
std::cout << *x << '\n';
}
return 0;
}
You can use a comparator like this:
// Simple class
class Person {
public:
string name;
Person(string name) {
this->name = name;
}
};
// create a comparator like this with two objects as parameters.
bool comparator(Person* a, Person *b) {
return a->name > b->name;
}
int main() {
vector<Person* > v;
v.push_back(new Person("ajay"));
v.push_back(new Person("tanya"));
// pass the comparator created into sort function.
sort(v.begin(), v.end(),comparator);
// printing output to check
for(int i=0;i<v.size();i++) {
cout<<v[i]->name<<endl;
}
}

How to get an index number by struct id in vector

struct person{
int p_id;
};
std::vector<person> people;
person tmp_person;
tmp_person.p_id = 1;
people.push_back(tmp_person);
person tmp_person2;
tmp_person2.p_id = 2;
people.push_back(tmp_person2);
person tmp_person3;
tmp_person3.p_id = 3;
people.push_back(tmp_person3);
How can I find a index number of vector people by the person's id.
For example, how can I get a index number of a person who has p_id 2?
Use std::find_if to find the element. This returns an iterator to the element. And if you really want to know the index use std:distance:
int id_to_find = 1;
std:size_t found_idx = std::distance(
std::begin(people),
std::find_if(std::begin(people), std::end(people),
[=] (const person& p) { return p.p_id == id_to_find; })
);
But you should really use iterators in C++ unless you have a good reason to want indexes.
Search in the vector using for loop.
for(int i=0;i<people.size();i++){
if(people[i].p_id == 2){
return i
break;
}
}
Solution using find_if
#include <iostream> // std::cout
#include <algorithm> // std::find_if
#include <vector> // std::vector
int val=2;
struct person{
int p_id;
};
bool isValue (struct person i) {
return ((i.p_id)==val);
}
int main () {
std::vector<struct person> people;
person tmp_person;
tmp_person.p_id = 1;
people.push_back(tmp_person);
person tmp_person2;
tmp_person2.p_id = 2;
people.push_back(tmp_person2);
person tmp_person3;
tmp_person3.p_id = 3;
people.push_back(tmp_person3);
std::vector<person>::iterator it = std::find_if (people.begin(), people.end(), isValue);
std::cout << "The index of value is " << it-people.begin() << '\n';
return 0;
}

Comparing Items in QList qt5.3

I am trying to compare the items in a QList.
Here is the old way to do it using QPtrCollection but this cannot be used in versions after qt3 (as far as I'm aware).
class gnyComponentList:public QList<gnyComponent>
{
protected:
virtual int compareItems ( QPtrCollection::Item item1, QPtrCollection::Item item2 )
{ return (((gnyComponent *)item1)->getID()).compare(((gnyComponent *)item2)->getID());}
};
I can't figure out what a good way of doing this in Qt5.3 might be?
You can use the std::equal algorithm on QList objects, as in:
#include <QList>
#include <QString>
#include <algorithm> // for std::equal
struct Person
{
QString firstName;
QString lastName;
};
int main()
{
QList<Person> personsA, personsB;
// Populate personsA and personsB
bool equal = std::equal( personsA.begin(), personsA.end(),
personsB.begin(),
[]( const Person &a, const Person & b ) {
return a.firstName == b.firstName;
} );
}
This is a simple one, which compares every item without sorting.
Here is the code.
bool TeachTab::isTwoStringListEqual(const QStringList &dst,
const QStringList &src) {
if (dst.size() != src.size())
return false;
for (int i = 0; i < dst.size(); ++i) {
if (dst.value(i) != src.value(i)) {
return false;
}
}
return true;
}

Sort STL list with single overloaded operator <

I have successfully populated linked list with data from a text file. Linked list contains structure that has 5 fields of type string.
I wish to sort the list by a certain structure field ( ascending or descending ). I have decided to overload operator< but I do not know how to implement it.
So far I am able to sort list by one fixed field. Here is the relevant code:
#include <iostream>
#include <list> // std::list
#include <fstream> // std::ifstream, std::ofstream
#include <string> // std::string
#include <algorithm> // std::remove, std::remove_if
#include <sstream> // std::istringstream
class Lista
{
private:
struct Person
{
// data from file
std::string lastName; // other fields omitted for keeping brevity
// operator < ( needed for correctly sorting the linked list )
bool operator< ( const Person &p )const
{
return lastName > p.lastName;
}
// constructor / destructor ... omitted for keeping brevity
};
// linked list that holds all the data from files
std::list<Person> persons;
public:
// constructor / destructor ... omitted for keeping brevity
// method for sorting the list
void sortList()
{
persons.sort();
}
};
I would like to add enum of choices, so I can use only one overloaded operator< for sorting.
Something like this:
class Lista
{
private:
struct Person
{
//================ here I could add enum of choices ============//
enum choice { FIELD1, LASTNAME, FIELD2 }; // you get the point
bool ascending; // decides if it is ascending or descending
//==============================================================//
// data from file
std::string lastName; // other fields omitted for keeping brevity
// operator < ( needed for correctly sorting the linked list )
bool operator< ( const Person &p )const
{
if ( choice == FIELD1 )
return field1 < p.field1;
if ( choice == FIELD2 )
return field2 < p.field2;
if ( choice == LASTNAME )
return lastName > p.lastName;
}
// constructor / destructor ... omitted for keeping brevity
};
// linked list that holds all the data from files
std::list<Person> persons;
public:
// constructor / destructor ... omitted for keeping brevity
// method for sorting the list
void sortList( Person::choice ch, bool ascending)
{
// here I should use the parameters to invoke proper sorting
persons.sort();
}
EDIT:
I have tried changing operator< into a function but have failed:
// this function is inside of my private struct
bool compare( const Person &p1, const Person &p2 )const
{
return p1.lastName > p2.lastName;
}
Then I called it in method like this:
void sortList()
{
persons.sort( compare );
}
But I get the following error: error C2065: 'compare' : undeclared identifier
I really have no other ideas on how to do this, can you please help me?
enum sort_choice { FIELD1, LASTNAME, FIELD2 } ; // had to put it outside to make it accessible to main()
class Lista
{
private:
struct Person
{
std::string field1;
std::string field2;
std::string lastName;
Person(const string& f1,const string& f2,const string& lname)
{
field1=f1;
field2=f2;
lastName=lname;
}
};
struct cmp_Person // A functor for comparison
{
bool cmp_ascending;
sort_choice cmp_choice;
cmp_Person(const bool& asc,const sort_choice& ch)
{
cmp_ascending=asc;
cmp_choice=ch;
}
bool operator ()(const Person &first, const Person& second) const
{
if(cmp_ascending)
{
if ( cmp_choice == sort_choice::FIELD1 )
return first.field1 < second.field1;
if ( cmp_choice == sort_choice::FIELD2 )
return first.field2 < second.field2;
if ( cmp_choice == sort_choice::LASTNAME )
return first.lastName > second.lastName;
}
else
{
if ( cmp_choice == sort_choice::FIELD1 )
return first.field1 > second.field1;
if ( cmp_choice == sort_choice::FIELD2 )
return first.field2 > second.field2;
if ( cmp_choice == sort_choice::LASTNAME )
return first.lastName > second.lastName;
}
return true;
}
};
std::list<Person> persons;
public:
void sortList( const bool& ascending, const sort_choice& ch)
{
persons.sort(cmp_Person(ascending,ch));
}
void push_to_list(const string& f1,const string& f2,const string& lname)
{
persons.push_back(Person(f1,f2,lname));
}
void display_list()
{
list<Person>::iterator it;
for(it=persons.begin(); it!=persons.end(); it++)
{
cout<<(*it).field1<<" "<<(*it).field2<<" "<<(*it).lastName<<"\n";
}
}
};
int main()
{
Lista Lobj;
Lobj.push_to_list("a","b","c");
Lobj.push_to_list("d","e","f");
Lobj.push_to_list("g","h","i");
Lobj.push_to_list("j","k","l");
Lobj.sortList(true,sort_choice::FIELD1);
Lobj.display_list();
cout<<"\n\n";
Lobj.sortList(false,sort_choice::FIELD1);
Lobj.display_list();
}
You can use something like this :
class Lista
{
public:
enum class Sort_Type{Name,LastName};
void sort(Sort_Type type,bool asc=true)
{
switch (type) {
case Sort_Type::Name:
this->list_.sort([&](const Person& p1,const Person& p2){
if(asc)
return p1.name.compare(p2.name)>=0 ;
else
return p1.name.compare(p2.name)<0;
});
break;
case Sort_Type::LastName :
this->list_.sort([&](const Person& p1,const Person& p2){
if(asc)
return p1.lastName.compare(p2.lastName)>=0 ;
else
return p1.lastName.compare(p2.lastName)<0;
});
break;
}
}
private:
struct Person
{
string name ;
string lastName;
};
std::list<Person> list_;
};
//
Lista l;
l.sort(Lista::Sort_Type::Name);

Error C2039: 'next' : is not a member of 'chain<T>' with [T=Person] [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm working on implementing a chain data structure, using a specific set of pre-made templates. Upon compilation, I'm receiving the error in the title.
arrayList.h:
#ifndef arrayList_h
#define arrayList_h
#include <iostream>
#include "linearList.h"
using namespace std;
template<class T>
class arrayList : public linearList<T>{
public:
//constructor, copy constructor, destructor
arrayList(int initialCapacity = 10);
arrayList(const arrayList<T>&);
~arrayList() {delete [] element;};
//ADT methods
bool empty() const {return listSize == 0;};
int size() const {return listSize;};
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(ostream& out) const;
//additional method
int capacity() const {return arrayLength;};
protected:
void checkIndex(int theIndex) const;
//throw illegalIndex if theIndex is invalid
T* element; //1D array to hold list elements
int arrayLength; //capacity of 1D array
int listSize; //number of elements in list
};
#endif
chain.h:
#ifndef chain_h
#define chain_h
#include <iostream>
#include "linearList.h"
#include "chainNode.h"
using namespace std;
template<class T>
class chain : public linearList<T>{
public:
// constructor and destructor
chain(int initialCapacity = 10);
//chain(const chain<T>&);
~chain();
// ADT methods
bool empty() const {return listSize == 0;}
int size() const {return listSize;}
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(ostream& out) const;
protected:
void checkIndex(int theIndex) const;
chain<T>* firstNode;
int listSize;
};
#endif
chainNode.h:
#ifndef chainNode_h
#define chainNode_h
#include <iostream>
template <class T>
struct chainNode
{
// data members
T element;
chainNode<T> *next;
// methods
chainNode() {}
chainNode(const T& element)
{this->element = element;}
chainNode(const T& element, chainNode<T>* next)
{this->element = element;
this->next = next;}
};
#endif
chain.cpp:
#include "chain.h"
#include "person.h"
using namespace std;
template<class T>
chain<T>::chain(int initialCapacity){
// Constructor.
/*if (initialCapacity < 1){
ostringstream s;
s << "Initial capacity = "
<< initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}*/
firstNode = NULL;
listSize = 0;
}
template<class T>
chain<T>::~chain(){
// Chain destructor. Delete all nodes
// in chain.
while (firstNode != NULL){
// delete firstNode
chainNode<T>* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
template<class T>
T& chain<T>::get(int theIndex) const{
// Return element whose index is theIndex.
checkIndex(theIndex);
// move to desired node
chainNode<T>* currentNode = firstNode;
for (int i = 0; i < theIndex; i++)
currentNode = currentNode->next;
return currentNode->element;
}
template<class T>
int chain<T>::indexOf(const T& theElement) const{
// search the chain for theElement
chainNode<T>* currentNode = firstNode;
int index = 0; // index of currentNode
while (currentNode != NULL && currentNode->element != theElement){
// move to next node
currentNode = currentNode->next;
index++;
}
// make sure we found matching element
if (currentNode == NULL)
return -1;
else
return index;
}
template<class T>
void chain<T>::erase(int theIndex){
checkIndex(theIndex);
chainNode<T>* deleteNode;
if (theIndex == 0){
// remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else{
// use p to get to beforeNode
chainNode<T>* p = firstNode;
for (int i = 0; i < theIndex - 1; i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next;
}
listSize--;
delete deleteNode;
}
template<class T>
void chain<T>::insert(int theIndex, const T& theElement){
if (theIndex < 0 || theIndex > listSize){
// THROW ILLEGAL EXCEPTION
}
if (theIndex == 0) // insert at front
firstNode = new chainNode<T>(theElement, firstNode);
else{
// find predecessor of new element
chainNode<T>* p = firstNode;
for (int i = 0; i < theIndex - 1; i++)
p = p->next;
// insert after p
p->next = new chainNode<T>(theElement, p->next);
}
listSize++;
}
Person.h:
#ifndef Person_h
#define Person_h
#include <string>
#include <sstream>
using namespace std;
class Person{
public:
//Variables
string birthdate;
string first_name;
string last_name;
string hometownID;
string hometownName;
string userID;
string name;
//Constructors
Person();
Person(string birthdate, string first_name, string last_name, string hometownID, string hometownName, string userID);
//Methods
string getBirthdate();
void setBirthdate(string birthdate);
string getFirst_name();
void setFirst_name(string first_name);
string getLast_name();
void setLast_name(string last_name);
string getName();
void setName(string name);
string getHometownID();
void setHometownID(string hometownID);
string getHometownName();
void setHometownName(string hometownName);
string getUserID();
void setUserID(string userID);
int compare(Person& p, int criteria);
//Comparisons
friend bool operator== (Person p1, Person p2);
friend bool operator!= (Person &p1, Person &p2);
friend bool operator> (Person &p1, Person &p2);
friend bool operator>= (Person &p1, Person &p2);
friend bool operator< (Person &p1, Person &p2);
friend bool operator<= (Person &p1, Person &p2);
friend ostream& operator<<(ostream& os, const Person& p);
};
#endif
Person.cpp: I've cut this down quite a bit. I currently don't have anything having to do with Node within this.
#include "Person.h"
#include <sstream>
#include <string>
using namespace std;
Person::Person(){
birthdate = "";
name = "";
hometownID = "";
hometownName = "";
userID = "";
}
Person::Person(string birthdate, string first_name, string last_name, string hometownID, string hometownName, string userID){
this->birthdate = birthdate;
this->first_name = first_name;
this->last_name = last_name;
this->hometownID = hometownID;
this->hometownName = hometownName;
this->userID = userID;
name = last_name+ ", " +first_name;
}
//mostly get/set methods after here, nothing having to do with node.
main.cpp:
#include "arrayList.cpp"
#include "block_allocator.h"
#include "chain.cpp"
#include "chainNode.h"
#include "json.h"
#include "linearList.h"
#include "Person.h"
#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <time.h>
using namespace std;
//ArrayList helper methods
arrayList<Person> arrayListStructure(string fileName);
int arrayListSort(int criteria, arrayList<Person>* list);
void arrayListReverseSort(int criteria, arrayList<Person>* list);
int arrayListFlip(arrayList<Person>* list);
//Chain helper methods
chain<Person> chainStructure(string fileName);
//Hashtable helper methods
int main(int argc, const char * argv[]){
//get fileName
cout << "Please enter a filename:" << endl;
string fileName;
cin >> fileName;
//get data structure type
cout << "Please choose a data structure:" << endl;
cout << " 1. Arraylist" << endl;
cout << " 2. Chain" << endl;
cout << " 3. Hashtable" << endl;
int dataStructure;
cin >> dataStructure;
cout << "Please choose a criteria:" << endl;
cout << " 1. Name" << endl;
cout << " 2. Birthday" << endl;
cout << " 3. Location" << endl;
int criteria;
cin >> criteria;
arrayList<Person> friends;
chain<Person> friendChain;
//parse file into data structure
switch(dataStructure){
case 1: //Arraylist
//edited out, irrelevant
/*case 2:
//Chain
//code goes here
/*switch(criteria){
case 1: //Name
case 2: //Birthday
case 3: //Location
}
break;*/
/*case 3:
//Hashtable
//code goes here
break;
*/
}
}
//Helper methods for chain
chain<Person> chainStructure(string fileName){
//create initial (empty) chain
chain<Person> friends;
//open input file
ifstream fileInput(fileName);
//turn input stream into string
string inputStr((istreambuf_iterator<char>(fileInput)), istreambuf_iterator<char>());
//parse file content into json object
char *errorPos = 0;
char *errorDesc = 0;
int errorLine = 0;
block_allocator allocator(1 << 10);
json_value *root = json_parse(const_cast<char*>(inputStr.c_str()), &errorPos, &errorDesc, &errorLine, &allocator);
//Take value of first element
json_value *list = root->first_child;
//Outer loop addresses each friend's JSON object
for(json_value *it = list->first_child; it; it = it->next_sibling){
string first_name, last_name, birthdate, hometownID, hometownName, userID;
//Inner loop looks at each key/value pair within each friend object
for(json_value *friendKeys = it->first_child; friendKeys; friendKeys = friendKeys->next_sibling){
//grab first name
if(!string(friendKeys->name).compare("first_name")){
first_name = friendKeys->string_value;
}
//grab last name
else if(!string(friendKeys->name).compare("last_name")){
last_name = friendKeys->string_value;
}
//grab birthday and trim to 5 characters
else if(!string(friendKeys->name).compare("birthday")){
birthdate = friendKeys->string_value;
birthdate = birthdate.substr(0, 5);
}
//grab hometown info
else if(!string(friendKeys->name).compare("hometown")){
for(json_value *hometownKeys = friendKeys->first_child; hometownKeys; hometownKeys = hometownKeys->next_sibling){
if(!string(hometownKeys->name).compare("id")){
hometownID = hometownKeys->string_value;
}
if(!string(hometownKeys->name).compare("name")){
hometownName = hometownKeys->string_value;
}
}
}
//grab userID
else if(!string(friendKeys->name).compare("id")){
userID = friendKeys->string_value;
}
}
if(birthdate != "" && first_name != "" && last_name != "" && hometownID != "" && hometownName != "" && userID != ""){
//Create new Person in chain
Person person(birthdate, first_name, last_name, hometownID, hometownName, userID);
friends.insert(friends.size(), person);
}
}
//return friends;
return friends;
}
//Helper methods for hashtable
So I know this is a huge wall of text, but I'm really not sure where this disconnect is, and I didn't want to provide too little information. Any help or advice would be greatly appreciated, as I'm very new to C++, and even more inexperienced with using the template system.
EDIT: linearList.h:
#ifndef linearList_h
#define linearList_h
#include <iostream>
using namespace std;
template<class T>
class linearList
{
public:
virtual ~linearList() {};
virtual bool empty() const = 0;
// return true iff list is empty
virtual int size() const = 0;
// return number of elements in list
virtual T& get(int theIndex) const = 0;
// return element whose index is theIndex
virtual int indexOf(const T& theElement) const = 0;
// return index of first occurence of theElement
virtual void erase(int theIndex) = 0;
// remove the element whose index is theIndex
virtual void insert(int theIndex, const T& theElement) = 0;
// insert theElement so that its index is theIndex
virtual void output(ostream& out) const = 0;
// insert list into stream out
};
#endif
In chain.h, the chain<T> template has this for a member:
chain<T>* firstNode;
I'm pretty sure that should be:
chainNode<T>* firstNode;
There may be other errors (or maybe not), but that appears the likely one causing your current issue that is the subject of this question.
Side Bar: This thing needs a serious refactor to use the containers and algorithms from the standard library (std::vector<T>, std::list<T>, etc...) Just consider it.