I am receiving a compiler error that I don't understand, and don't know how to deal with it properly. If anyone could offer me some advice on how to fix it I would be much appreciated. The error reads:
Error 1 error C2664: 'char myVector<char>::at(T &) const' : cannot convert argument 1 from 'int' to 'char &'
It's on line 159 of the header code where it reads out << rho.at(n);.
Driver:
#include <iostream>
#include "vectorHeader.h"
using namespace std;
int main()
{
const char START = 'A';
const int MAX = 12;
// create a vector of doubles
myVector<char> vectD;
// push some values into the vector
for (int i = 0; i < MAX; i++)
{
vectD.push_back(START + i);
}
// remove the last element
vectD.pop_back();
// add another value
vectD.push_back('Z');
// test memory management
myVector<char> vectD2 = vectD;
// display the contents
cout << "\n[";
for (int i = 0; i < vectD2.size() - 1; i++)
{
cout << vectD2[i] << ", ";
}
cout << "..., " << vectD2.last() << "]\n";
system("PAUSE");
return 0;
}
Header:
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <fstream>
#include <stdexcept>
//Declaring constant
const int VECTOR_CAP = 2;
template <class T>
class myVector
{
private:
//Setting data members
T* vectorData;
int cap;
int numElements;
public:
//Default constructor
//Purpose: Creates a vector
//Parameters: None
//Returns: None
myVector();
//Parameterized constructor
//Purpose: Creates a vector capacity of n
//Parameters: None
//Returns: None
myVector(const T&);
//Copy Constructor
//Purpose: Copy data into vector
//Parameters: myVector object
//Returns: None
myVector(const myVector& copy)
{
numElements = copy.numElements;
vectorData = new T [numElements];
for (int i = 0; i < numElements; i++)
{
this->vectorData[i] = copy.vectorData[i];
}
}
//Destructor
//Purpose:Deletes any dynamically allocated storage
//Parameters: None
//Returns: None
~myVector();
//Size function
//Purpose: returns the size of your vector
//Parameters: None
//Returns: The size of your vector as an integer
int size() const;
//Capacity function
//Purpose: Returns the capacity of the vector
//Parameters: None
//Returns: Maximum value that your vector can hold
int capacity() const;
//Clear function
//Purpose: Deletes all of the elements from the vector and resets its size to zero
// and its capacity to two; thus becoming empty
//Parameters: None
//Returns: None
void clear();
//push_back function
//Purpose: Adds the integer value n to the end of the vector
//Parameters: Takes a integer to be placed in the vector
//Returns: None
void push_back(const T& n)
{
//If statement to handle if array is full
if (numElements == cap)
{
//Doubling the capacity
cap = cap * VECTOR_CAP;
//Allocating new array
T* newVectorData = new T[cap];
//Copying data
for (int i = 0; i < numElements; i++) newVectorData[i] = vectorData[i];
//Deleting previous data
delete[] vectorData;
//Pointing to new data
vectorData = newVectorData;
}
//Storing data
vectorData[numElements++] = n;
}
//at function
//Purpose: Returns the value of the element at position n in the vector
//Parameters: None
//Returns: Returns your current place with the vector
T at(T&) const;
//assignment
//Purpose: Overload the = operator
//Parameters: The two myVector objects we want to assign
//Returns: The assignment
myVector operator=(const myVector&);
void pop_back();
int last();
myVector operator[](const myVector&);
};
//Independant Functions
template <typename T>
int myVector<T>::capacity() const
{
return cap;
}
template <typename T>
myVector<T> myVector<T>::operator=(const myVector& rho)
{
//Test for assingment
if (this == &rho)
{
return *this;
}
//Delete lho
delete[] this->vectorData;
//Creating new array to fit rho data
cap = rho.cap;
this->vectorData = new int[cap];
//Copying data
for (int i = 0; i < numElements; i++)
{
this->vectorData[i] = rho.vectorData[i];
}
//Returning myVector object
return *this;
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const myVector<T>& rho)
{
for (int n = 0; n < rho.size(); n++)
{
out << rho.at(n);
}
return out;
}
Exactly what it says on the tin. When you have
T at(T&) const;
in a myVector<char>, that translates to
char at(char&) const;
and an int cannot be bound to a reference to char. I think you meant to say
T at(int) const;
or, better,
T at(std::size_t) const;
because std::size_t is usually (by convention) used for this sort of thing. int is implicitly convertible to std::size_t, so that will also just work.
Your declaration of myVector::at(T&) takes the templated type as an argument. You need to declare it as
T at(unsigned int&) const
That way you can use the parameter as an index.
Related
I'm having a bit of trouble wrapping this around my head; I used the debugger in VS to go through my code. I realized that when I call the insertBack() function in main() the elements aren't inserted since the condition if (!isFull) isn't met--returning false causing the insertion to not happen. I tried removing the condition and got some errors regarding my code trying to insert a number into an invalid portion of the array. While going through this, I started to ask myself is the isFull() function required since a dynamic array can be resized; but, how can it be full if this is the case? I looked a bit into vectors on cpprefrence and didn't find an isFull() member function.
#include <iostream>
template<typename T>
class container
{
template <typename T2>
friend std::ostream& operator<<(std::ostream& out, const container<T2> &cobj);
// Postcondition: contents of the container object cobj is displayed
public:
container();
// Postcondition: an empty container object is created with data members arr set to NULL, n set to -1 and Capacity set to 0
~container();
// Destructor; required as one of the Big-3 (or Big(5) because of the presence of a pointer data member. Default version results in
// memory leak!
// Postcondition: dynamic memory pointed to by arr has been release back to the “heap” and arr set to NULL or nullptr
// In order to see the action, message "destructor called and dynamic memory released!" is displayed
bool isEmpty() const;
// Postcondition: returns true is nothing is stored; returns false otherwise
bool isFull() const;
// Postcondition: returns true if arr array is filled to capacity; returns false otherwise
int size() const;
// Postcondition: returns the size or the number of elements (values) currently stored in the container
int capacity() const;
// Postcondition: returns the current storage capacity of the container
bool insertBack(const T& val);
// Postcondition: if container is not full, newVal is inserted at the end of the array;
// otherwise, double the current capacity followed by the insertion
bool deleteBack();
// Precondition: The array must not be empty
// Postcondition: the last element stored in the array is removed! size of the container is decremented by 1, capacity unchanged
void clear();
// Postcondition: all elements in arr of calling container object are cleared and the dynamic memory is released back to “heap”
private:
void allocate(T* &temp);
// Postcondition: if Capacity = 0, allocate a single location; otherwise the current capacity is doubled
T *arr;
int Capacity; // Note: Capital 'C' as capacity is used as a function name
int n; // size or actual # of values currently stored in the container; n <= SIZE
};
template<typename T2>
std::ostream& operator<<(std::ostream& out, const container<T2> &cobj)
{
std::cout << "Currently it contains " << cobj.size() << " value(s)" << std::endl
<< "Container storage capacity = " << cobj.capacity() << std::endl
<< "The contents of the container:" << std::endl;
if (cobj.isEmpty())
{
std::cout << "*** Container is currently empty!" << std::endl;
}
else
{
for (int i=0; i<cobj.size(); ++i)
{
std::cout << cobj.arr[i];
}
}
return out;
}
template<typename T>
container<T>::container()
{
arr = nullptr;
Capacity = 0;
n = 0;
}
template<typename T>
container<T>::~container()
{
delete arr;
arr = nullptr;
std::cout << "Destructor called! (this line is normally not displayed)" << std::endl;
}
template<typename T>
bool container<T>::isEmpty() const
{
return n==0;
}
template<typename T>
bool container<T>::isFull() const
{
return n==Capacity;
}
template<typename T>
int container<T>::capacity() const
{
return Capacity;
}
template<typename T>
int container<T>::size() const
{
return n;
}
template<typename T>
bool container<T>::insertBack(const T& val)
{
if (!isFull())
{
n++;
arr[n-1] = val;
return true;
}
else
{
return false;
}
}
template<typename T>
bool container<T>::deleteBack()
{
if (!isEmpty())
{
n--;
return true;
}
else
{
return false;
}
}
template<typename T>
void container<T>::clear()
{
if (!isEmpty())
{
n = 0;
return true;
}
else
{
return false;
}
}
template<typename T>
void container<T>::allocate(T* &temp)
{
if (Capacity==0)
{
temp = new T;
}
else
{
return Capacity*2;
}
}
int main()
{
container<int> a1;
std::cout << a1 << std::endl;
std::cout << "Currently, the container object contains 0 element(s) or 0 value(s)" << std::endl;
std::cout << "\nWe now insert 3 values at the back of the array, one at a time:" << std::endl;
const int num = 3;
for (int i=0, c=0; i<=num; ++i, c+=10)
{
a1.insertBack(c);
}
std::cout << a1;
}
I think that having an isFull method does not make sense, since your dynamic container is not limited in capacity. Instead, you can use the size and capacity methods to track the state of the container.
If you want to implement a vector and want to check if size smaller than or equals to capacity, then decide whether to resize it, you can wrapper size > = capacity as a private isFull() function. But I think it makes no sense to set it public.
I'm writting an IntArray class for college but don't know how to write my resize method efficiently. What I have doesn't support resizing to smaller lists and I don't know how to fix that..
Here is my code:
void IntArray::resize(unsigned int size){
for (int i = size;i<length;i++){
data[i] = 0;
}
length = size;
}
header file
#ifndef INTARRAY_H_
#define INTARRAY_H_
#include <iostream>
using namespace std;
class IntArray{
private:
int length;
int * data;
public:
IntArray(int size = 0);
IntArray(const IntArray& other);
IntArray& operator=(const IntArray& original);
int getSize() const { return length; };
int& operator[](unsigned int i);
void resize(unsigned int size);
void insertBefore(int value, int index);
friend ostream& operator<<(ostream& out, const IntArray& list);
~IntArray(){ delete[] data; };
};
When you need to resize an you are actually going to create a new array, copy the old into the new and then delete the old array.
void IntArray::resize(unsigned int size){
if (size <= length) // if we are making it smaller reset the size and do nothnig
{
my_size = size
return;
}
int * temparr = new int[size];
// copy data
for (unsigned int i = 0; i < length; ++i)
temparr[i] = data[i];
delete [] data; // get rid of the old array
data = temparr; // set data to the new array
length = size; // set the new size
}
You should also have a capacity member that tracks the actual size of the array like a std::vector. That way you can have an array that is bigger than what you need to as it grows there would need to be less re -llocations.
So, I have a token class:
Token.h
class Token {
std::string name; // token name
int frequency;//frequency
Vector lines;//lines where the token is present
public:
//explanations for the methods in the Token.cpp
Token(std::string tokenname, int linenumber);
virtual ~Token();
const Vector getLines() const;
};
#endif /* TOKEN_H_ */
Token cpp
Token::Token(string tokenname, int linenumber) {
// TODO Auto-generated constructor stub
name = tokenname;
frequency=1;
lines.push_back(linenumber);
}
Token::~Token() {
// TODO Auto-generated destructor stub
}
std::string Token::getName() const{
return name;
}
int Token::getFrequency() const{
return frequency;
}
const Vector Token::getLines() const{
const Vector vec = lines;
return lines;
}
The program fails, when I pass it to the insert method of list class
class List {
private:
class Node {
public:
Token data;
Node* next;
Node(const Token &dataItem, Node* nextptr);
~Node();
};
Node* first;
int length;
public:
List();
virtual ~List();
void insert(const Token &t);
};
List.cpp:
List::Node::Node(const Token &dataItem, Node* nextptr): data(dataItem), next(nextptr){
}
List::Node::~Node(){
cout<<"dead"<<endl;
}
List::List() {
// TODO Auto-generated constructor stub
length = 0;
first = nullptr;
}
List::~List() {
// TODO Auto-generated destructor stub
Node* temp = first;
Node* newtmp;
while(temp->next != nullptr){
newtmp = temp->next;
delete temp;
temp = newtmp;
}
}
const int List::size(){
return length;
}
void List::insert (const Token &t){
Vector dammit = t.getLines();
}
I found out which line in the insert does it(Vector dammit = t.getLines()), so I leave it like that.
It gives me this error message:
double free or corruption (fasttop): 0x0000000000c34040 ***
And here something from main file if you want to run:
int main() {
// cout<<"tokens are here"<<endl;
//
Token hit("aca", 1);
Token hit2("ui", 2);
Token hit1("111", 3);
List list;
list.insert(hit);
list.insert(hit2);
list.insert(hit1);
}
Vector class:
class Vector {
int* store;
int capacity;
int next_index;
public:
Vector();
Vector(int initial_size);
Vector(const Vector &v);
virtual ~Vector();
void push_back(int item);
int pop_back();
const int size() const;
void resize();
void operator =(const Vector &v);
int& operator[] (int k);
const int& operator[] (int k) const;
friend std::ostream& operator<<(std::ostream& os, const Vector& v);
};
Vector::Vector() {
// TODO Auto-generated constructor stub
store = new int [1];
capacity = 1;
next_index = 0;
}
Vector::Vector(int initial_size){
store = new int [initial_size];
capacity = initial_size;
next_index = 0;
}
Vector::Vector(const Vector &v){
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
Vector::~Vector() {
// TODO Auto-generated destructor stub
delete[] store;
}
void Vector::resize(){
std::cout<<"in resize"<<std::endl;
std::cout<<capacity<<std::endl;
int length = capacity;
capacity+=100;
int* tempArray;
tempArray = new int[capacity];
for (int i=0; i<length; i++){
tempArray[i] = store[i];
}
if (length>1)
delete[] store;
std::cout<<"finish re4size"<<std::endl;
store = tempArray;
}
void Vector::push_back(int item){
if(next_index >= capacity)
this->resize();
store[next_index] =item;
next_index++;
}
int Vector::pop_back(){
next_index = next_index-1;
int last = store[next_index];
return last;
}
void Vector::operator =(const Vector &v){
//delete[] store;
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
const int Vector::size() const{
return next_index-1;
}
int& Vector::operator[] (int k){
//assert((k<next_index)&(k>=0));
return store[k];
}
const int& Vector::operator[] (int k) const{
//assert((k<next_index)&(k>=0));
return store[k];
}
ostream& operator<<(ostream& os, const Vector& v)
{
for(int i=0; i<=v.size(); i++){
os << v[i]<< ' ';
}
return os;
}
In
Vector::Vector(const Vector &v){
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
You now have two vectors pointing to the same int* store;
In
void Vector::operator =(const Vector &v){
//delete[] store;
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
You do the same thing.
when you call
const Vector Token::getLines() const{
const Vector vec = lines;
return lines;
}
vec = lines uses the copy constructor. You now have vec and lines pointing to the same store.
You return a copy of lines, this will trigger the copy constructor again. A third object now points to store.
When the stack unrolls, locally defined vec is destroyed. ~Vector deletes store. You now have two objects pointing to the same de-allocated store.
Kaboom! as soon as you try to do much of anything else with either of those Vectors. Looks like the destruction of the returned Vector hits first and causes the destructor to re-delete store.
You need to allocate storage for a new store and then copy the contents of source store into the new store in the = operator and the copy constructor.
Vector::Vector(const Vector &v){
capacity = v.capacity;
store=new int[capacity];
for (size_t index; index < capacity; index++)
{
store[index] = v.store[index];
}
next_index = v.next_index;
}
and
Vector & Vector::operator =(const Vector &v){
delete[] store;
capacity = v.capacity;
store=new int[capacity];
for (size_t index; index < capacity; index++)
{
store[index] = v.store[index];
}
next_index = v.next_index;
}
std::copy can be used in place of the for loop in C++11. Hoary old memcpy can also be used, but only because store is a primitive data type.
And while I'm editing, thanks Jarod42, one more little tweak:
const Vector & Token::getLines() const{ //note the return of a reference. This avoids
// making a copy of lines unless the caller really
// wants a copy.
// const Vector vec = lines; don't need to do this. lines is const-ified by the
// const on the return type of the function
return lines;
}
This error has nothing to do with calling a method with constant reference, but rather the function getLines(). For example, should you take hit1 and call the function getLines() directly, it will crash nonetheless. The issue is with how Token has a stack-allocated attribute Vector, which in turn has an int * attribute. This isn't necessarily an issue, but depending on how you implement those classes it can cause memory conflicts.
If you want to keep using your getLine() and can't use the <vector> libraries, you could change your Token's lines attribute to a Vector * and change all other syntax accordingly. Also remember to initialize your pointer lines memory or else it will crash.
However, I'd prefer to use as less dynamic-allocated memory as possible, if unnecessary. And like another user said, before while(temp->next != nullptr) you should have a condition if(temp != nullptr )
I am not getting the expected output for the program that I have coded, I know that the implementation for the last function is incorrect. I don't know how to implement this so that it returns the last entry into the array, and doesn't remove it. The second question that I have is on the pop_back function, its supposed to remove last entry pushed into the vector and reduce it by one, and if it's empty do nothing. The way it is now it just reduces the vector by one. Thanks for your help in advance.
Driver
#include <iostream>
#include "vectorHeader.h"
using namespace std;
int main()
{
const char START = 'A';
const int MAX = 12;
// create a vector of doubles
myVector<char> vectD;
// push some values into the vector
for (int i = 0; i < MAX; i++)
{
vectD.push_back(START + i);
}
// remove the last element
vectD.pop_back();
// add another value
vectD.push_back('Z');
// test memory management
myVector<char> vectD2 = vectD;
// display the contents
cout << "\n[";
for (int i = 0; i < vectD2.size() - 1; i++)
{
cout << vectD2[i] << ", ";
}
cout << "..., " << vectD2.last() << "]\n";
system("PAUSE");
return 0;
}
Header
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <array>
//Declaring constant
const int VECTOR_CAP = 2;
template <class T>
class myVector
{
private:
//Setting data members
T* vectorData;
int cap;
int numElements;
public:
//Default constructor
//Purpose: Creates a vector
//Parameters: None
//Returns: None
myVector();
//Parameterized constructor
//Purpose: Creates a vector capacity of n
//Parameters: None
//Returns: None
myVector(const T&);
//Copy Constructor
//Purpose: Copy data into vector
//Parameters: myVector object
//Returns: None
myVector(const myVector& copy)
{
numElements = copy.numElements;
vectorData = new T [numElements];
for (int i = 0; i < numElements; i++)
{
this->vectorData[i] = copy.vectorData[i];
}
}
//Destructor
//Purpose:Deletes any dynamically allocated storage
//Parameters: None
//Returns: None
~myVector();
//Size function
//Purpose: returns the size of your vector
//Parameters: None
//Returns: The size of your vector as an integer
int size() const;
//Capacity function
//Purpose: Returns the capacity of the vector
//Parameters: None
//Returns: Maximum value that your vector can hold
int capacity() const;
//Clear function
//Purpose: Deletes all of the elements from the vector and resets its size to
// zero and its capacity to two; thus becoming empty
//Parameters: None
//Returns: None
void clear();
//push_back function
//Purpose: Adds the integer value n to the end of the vector
//Parameters: Takes a integer to be placed in the vector
//Returns: None
void push_back(const T& n)
{
//If statement to handle if array is full
if (numElements == cap)
{
//Doubling the capacity
cap = cap * VECTOR_CAP;
//Allocating new array
T* newVectorData = new T[cap];
//Copying data
for (int i = 0; i < numElements; i++) newVectorData[i] = vectorData[i];
//Deleting previous data
delete[] vectorData;
//Pointing to new data
vectorData = newVectorData;
}
//Storing data
vectorData[numElements++] = n;
}
//at function
//Purpose: Returns the value of the element at position n in the vector
//Parameters: None
//Returns: Returns your current place with the vector
T& at(std::size_t);
//assignment
//Purpose: Overload the = operator
//Parameters: The two myVector objects we want to assign
//Returns: The assignment
myVector operator=(const myVector&);
void pop_back();
int last();
T& operator[](std::size_t);
};
//Independant Functions
template <typename T>
myVector<T>::myVector()
{
//Setting the cap
cap = VECTOR_CAP;
//Creating the array
vectorData = new T[cap];
//Initializing the value
numElements = 0;
}
template <typename T>
myVector<T>::~myVector()
{
cap = 0;
//Delete array elements
delete[] vectorData;
//Allocate vectorData
vectorData = NULL;
}
template <typename T>
int myVector<T>::size() const
{
return numElements;
}
template <typename T>
void myVector<T>::pop_back()
{
numElements--;
}
template <typename T>
int myVector<T>::last()
{
return cap;
}
template <typename T>
int myVector<T>::capacity() const
{
return cap;
}
template <typename T>
T& myVector<T>::at(std::size_t n)
{
return vectorData[n];
}
template <typename T>
T& myVector<T>::operator[](std::size_t n)
{
return vectorData[n];
}
template <typename T>
myVector<T> myVector<T>::operator=(const myVector& rho)
{
//Test for assingment
if (this == &rho)
{
return *this;
}
//Delete lho
delete[] this->vectorData;
//Creating new array to fit rho data
cap = rho.cap;
this->vectorData = new int[cap];
//Copying data
for (int i = 0; i < numElements; i++)
{
this->vectorData[i] = rho.vectorData[i];
}
//Returning myVector object
return *this;
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const myVector<T>& rho)
{
for (int n = 0; n < rho.size(); n++)
{
out << rho.at(n);
}
return out;
}
The last function should look like this:
template <typename T>
T myVector<T>::last()
{
return vectorData[numElements - 1];
}
A function that returns an element from the vector should have the return type the type of the vector elements, i.e. T in your case.
cout has different overloads for char and int. For char it prints the ASCII character of the code provided, for int it returns the code itself. So if your last element is Z and you return an int it would print the ASCII code of Z that is 90.
try this to get a sense of what I am saying:
cout << 'Z' << endl;
cout << (char) 'Z' << endl; // tautological cast as 'Z' is char
cout << (int) 'Z' << endl;
cout << 90 << endl;
cout << (int) 90 << endl; // tautological cast as 90 is int
cout << (char) 90 << endl;
As for pop_back all you have to do is:
if (numElements > 0)
numElements--;
Reason: there is no such thing as deleting memory. A cell of memory always has a value (be it one you set, 0, 1 or garbage). All you have to do is mark it as being available (or not used). That's what you do when you shrink numElements.
If you want to go a step further you could do the opposite of push_back, i.e. relocate the whole vector to a smaller allocated buffer. But this is not advised as these operations (allocating, copying) are expensive and you can do without them (unlike pus_back where you have to get a bigger size)
I currently have a Person class, and have created a PersonList class that extends List, specifically for objects of type Person. When I instantiate a new PersonList I get one error that stops the entire build from happening successfully:
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Person' (or there is no acceptable conversion) c:\program files\microsoft visual studio 11.0\vc\include\xutility 3186 1 ConsoleApplication3
Here is the PersonList class:
#pragma once
#include<iostream>
#include<sstream>
#include<string>
#include<algorithm>
#include "linearList.h"
#include "myExceptions.h"
#include "changeLength1D.h"
#include <Person.h>
using namespace std;
template<class Person>
class PersonList: public linearList<Person>
{
public:
PersonList(int initialCapacity = 10);
PersonList(const PersonList<Person>&);
~PersonList() {delete [] element;}
bool empty() const {return listSize == 0;}
int size() const {return listSize;}
Person& get(int theIndex) const;
int indexOf(const Person& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const Person& theElement);
void output(ostream& out) const;
// additional method
int capacity() const {return arrayLength;}
protected:
void checkIndex(int theIndex) const;
// throw illegalIndex if theIndex invalid
Person* element; // 1D array to hold list elements
int arrayLength; // capacity of the 1D array
int listSize; // number of elements in list
};
template<class Person>
PersonList<Person>::PersonList(int initialCapacity)
{// Constructor.
if (initialCapacity < 1)
{ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
arrayLength = initialCapacity;
element = new Person[arrayLength];
listSize = 0;
}
template<class Person>
PersonList<Person>::PersonList(const PersonList<Person>& theList)
{// Copy constructor.
arrayLength = theList.arrayLength;
listSize = theList.listSize;
element = new Person[arrayLength];
copy(theList.element, theList.element + listSize, element);
}
template<class Person>
void PersonList<Person>::checkIndex(int theIndex) const
{// Verify that theIndex is between 0 and listSize - 1.
if (theIndex < 0 || theIndex >= listSize)
{ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
template<class Person>
Person& PersonList<Person>::get(int theIndex) const
{// Return element whose index is theIndex.
// Throw illegalIndex exception if no such element.
checkIndex(theIndex);
return element[theIndex];
}
template<class Person>
int PersonList<Person>::indexOf(const Person& theElement) const
{// Return index of first occurrence of theElement.
// Return -1 if theElement not in list.
// search for theElement
int theIndex = (int) (find(element, element + listSize, theElement)
- element);
// check if theElement was found
if (theIndex == listSize)
// not found
return -1;
else return theIndex;
}
template<class Person>
void PersonList<Person>::erase(int theIndex)
{// Delete the element whose index is theIndex.
// Throw illegalIndex exception if no such element.
checkIndex(theIndex);
// valid index, shift elements with higher index
copy(element + theIndex + 1, element + listSize,
element + theIndex);
element[--listSize].~Person(); // invoke destructor
}
template<class Person>
void PersonList<Person>::insert(int theIndex, const Person& theElement)
{// Insert theElement so that its index is theIndex.
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
// valid index, make sure we have space
if (listSize == arrayLength)
{// no space, double capacity
changeLength1D(element, arrayLength, 2 * arrayLength);
arrayLength *= 2;
}
// shift elements right one position
copy_backward(element + theIndex, element + listSize,
element + listSize + 1);
element[theIndex] = theElement;
listSize++;
}
template<class Person>
void PersonList<Person>::output(ostream& out) const
{// Put the list into the stream out.
copy(element, element + listSize, ostream_iterator<Person>(cout, " "));
}
// overload <<
template <class Person>
ostream& operator<<(ostream& out, const PersonList<Person>& x)
{x.output(out); return out;}
The Person Class:
#pragma once
#include <string>
using namespace std;
class Person
{
public:
Person(string firstName, string lastName, string birthday, string hometown);
Person(void);
~Person(void);
string name;
string birthday;
string hometown;
};
The same thing happens in an arrayList class I tried using earlier. Is there a way to get it so I can simply store person objects in an ArrayList type structure?
Your function indexOf() contains a call to STL's std::find() algorithm, which internally performs comparisons between pairs of values to determine if the element passed as a third argument is contained in the range defined by the first two arguments.
To perform this comparison, std::find() uses the == operator. However, no operator == has been defined for objects of type Person.
In order to solve the problem, you must overload the comparison operator == for instances of Person. You can do it, for instance, this way:
class Person
{
...
public:
friend bool operator == (Person const& p1, Person const& p2)
{
// Perform the comparison and return "true" if the objects are equal
return (p1.name == p2.name) && ...
}
};