C++ Graph data Structure - c++

I am writing a graph implementation in c++ where the cities are vertices, flights from one city to another city represent an edge, and the weights are the distances between those cities. The vertices,edges, and weights are stored in a file and when the program runs it would load the vertices, edges, and weights into the program. I am using an adjacency matrix where it represents the edges.
Now when the program runs it will prompt the user to either:
Choose Departure city
Exit. Option two just terminates the program.
If the user chooses option one, then it will list all the cities from the file. There a seven cities I chose. So it will look like 1.)Los Angeles 2.) New York 3.) Miami and so on until option 7. When the user chooses an option it will then list all the destination cities except the departure city the user chose. There would be three possibilities once the user chooses his destination city.
Now the first possibility would be there would be no direct or through connection between city A and city B and the program will output, No destination between [departure city] and [destination city] , press any key to return. Once the user presses any key, the menu will display again. The Second possibility would be if there is a direct connection between the city then the program would output the direct connection between [departure city]-[destination city] = [miles] and the miles between the city, or if there isn't a direct connection it will say no direct connection and the user can go back to the menu.
The third possibility would be that there would be a through connection and it will show the departure city and destination city with all the cities between them and the total miles it covers between them and the user can press any key to return to the menu.
Now the problem I"m having is getting the info from the file, I can't figure out how to get the info from the file or how to write the file so the program knows which are the vertices,edges,and weights. Also, how to display the cities and which have the direct connection, through connection, or no connection at all.
include <iostream>
#include <fstream>
#pragma once
const int NULL_EDGE = 0;
typedef std::string String;
class GraphType
{
private:
int edges[50][50];
int m_numVertices;
int m_maxVertices;
int m_distance;
String* m_vertices;
bool* marks; // marks[i] is the mark for vertices[i]
int IndexIs(String*, String);
public:
GraphType();
~GraphType();
bool isEmpty() const;
bool isFull(); //to do
int GetWeight(String, String); // to do
void ClearMarks(); // to do
void MarkVertex(String) // to do
bool isMarked(String) // to do
void addVertex(String);
void addEdge(String, String, int);
void displayCities();
};
#include "GraphType.h"
GraphType::GraphType()
{
m_maxVertices = 50;
m_distance = 0;
m_vertices = new String[m_maxVertices];
marks = new bool[50];
std::ifstream loadFile;
loadFile.open("load.txt");
if (loadFile.fail())
std::cout << " Error opening load.txt\n";
else
{
//stuck here
}
loadFile.close();
}
GraphType::~GraphType()
{
delete[] m_vertices;
delete[] marks;
}
int GraphType::IndexIs(String* vertices, String vertex)
{
int index = 0;
while (!(vertex == m_vertices[index]) == 0)
index++;
return index;
}
void GraphType::addVertex(String vertex)
{
m_vertices[m_numVertices] = vertex;
for (int i = 0; i < m_numVertices; i++)
{
edges[m_numVertices][i] = NULL_EDGE;
edges[i][m_numVertices] = NULL_EDGE;
}
m_numVertices++;
}
void GraphType::addEdge(String startVertex, String destVertex, int weight)
{
int row;
int col;
row = IndexIs(m_vertices, startVertex);
col = IndexIs(m_vertices, destVertex);
edges[row][col] = weight;
}
void GraphType::displayCities()
{
//stuck here
}
bool GraphType::isEmpty() const
{
return (m_numVertices == 0);
}
#include "GraphType.h"
int FlyMenu();
void CitiesMenu(GraphType&);
int main()
{
int choose;
GraphType gt;
do
{
choose = FlyMenu();
switch (choose)
{
case 1: CitiesMenu(gt);
break;
case 2:
break;
default: std::cout << " Invalid Input\n";
break;
}
} while (choose != 2);
return 0;
}
int FlyMenu()
{
int option;
std::cout << " 1.) Choose Depature City\n";
std::cout << " 2.) Exit\n";
std::cout << " Enter option: ";
std::cin >> option;
return option;
}
void CitiesMenu(GraphType& gt)
{
gt.displayCities();
}
I know about the depth Traversal and breadth Traversal algorithms to see if there is a connection between a city or not, but I don't know how to implement them for this scenario. I can't use the Standard Template Library, only std::vector. I was thinking about writing another class, but I don't know what what that class will help me with.

From what I got you have two questions:
read / write from file: the simplest solution would be freopen.
freopen("input","r",stdin)
freopen("output","w",stdout)
now every cin & cout operation will be done on the files you defined on freopen
implementing DFS / BFS: I will code the simplest type of DFS for you and you have to edit it to suite you program.
bool visit[MAX_CITY + 10];
void DFS(int x){
visit[x] = 1;
for (int i=1;i<=MAX_CITY;i++){
int nx = i;
if (adj[x][i] == -1) continue; // a cost of -1 means no flight
if (visit[nx]) continue;
DFS(nx);
}
}

Related

How do you compare and sort a specific parameter within a class?

My professor has asked us to make a program that will take a user's input and continue reading until the end of input. Only then, can the program output what the user has typed.
Input should be based on video title, it's url, comments made on the video, length (in minutes), and rating (in *).
For example:
United Break Guitars, https://www.youtube.com/watch?v+5YGc4zOqozo, Great example of one person getting a giant company to listen, 4.5, ***, Space Versus Tabs, https://www.youtube.com/watch?v=SsoOG6ZeyUl, Decide for yourself: spaces or tabs?, 2.83, ****
Up until what is explained, I have completed and tested to see if everything works. My problem is the next part of the project which requires the user to choose between Rating, Length, or title then sort them based on what the user chose.
If I chose Rating, then the input above should be sorted from highest rated video to lowest.
This is what I have so far:
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
using namespace std;
#include "video.h"
int main()
{
string user, url, comment, title;
int rating;
double length;
int i = 0, last = 0;
Video *videoObj[100];
Video *temp[100];
// specifies how the videos should be sorted
cin >> user;
cin.ignore();
while (getline(cin,title) ) {
getline(cin, url);
getline(cin, comment);
cin >> length;
cin >> rating;
cin.ignore();
videoObj[i] = new Video(title, url, comment, length, rating);
i++;
last++;
}
temp[i] = new Video(title, url, comment, length, rating);
if(user=="rating"){
for(int i = 0; i < last - 1; i++){
for(int j = i+1; j< last; j++){
if(videoObj[i] -> Rating(videoObj[j])) {
temp[i] = videoObj[i];
videoObj[i]= Rating(videoObj[j]);
Rating(videoObj[j]) = temp[i];
}
}
}
}
for(int i= 0; i < last; i++)
{
videoObj[i]->print();
}
//delete[] videoObj;
return 0;
}
video.cpp file:
#include <iostream>
#include <algorithm>
using namespace std;
#include "video.h"
Video::Video(string video_title, string video_link, string video_comment, double video_length, int video_number)
: title(video_title), link(video_link), comment(video_comment), length(video_length), rating(video_number)
{
}
bool Video::Rating(Video *videoObj) {
if(rating > videoObj-> rating )
{
return true;
}
else
{
return false;
}
}
void Video::print(){
string star;
switch(rating){
case 1:
star = "*";
break;
case 2:
star = "**";
break;
case 3:
star = "***";
break;
case 4:
star = "****";
break;
case 5:
star = "*****";
break;
}
cout << title << ", " << link << ", " << comment << ", " << length << ", " << star << endl;
}
void Video::temp(){
title, link, comment, length, rating;
}
video.h file:
#ifndef VIDEO_H
#define VIDEO_H
using namespace std;
class Video {
public:
Video(string video_title, string video_link, string video_comment, double video_length, int video_number);
void print();
bool Rating(Video *videoObj);
void temp();
private:
string title;
string link;
string comment;
double length;
int rating;
};
#endif
I honestly have no idea how to implement the bubble sort correctly. I have looked up multiple different videos on youtube and posts on stackoverflow, but I can't seem to figure out how to sort a specific parameter within my class.
My professor gave us these instructions for sorting within our class:
When sorting the videos you need to be able to determine how two video objects should be
ordered. The easiest way to do this is to write member functions to handle the comparisons in
class Video. For example, this method could be used when sorting the videos by length:
// return true if the current video is longer than the given video (other) ,
// otherwise return false
bool Video :: longer(Video *other) {
return (mlength > other -> mlength ;
}
I'm not even sure if I did that part correctly in my video.cpp file. Any ideas on how I can get the sorting method to work properly?
Please be gentle, I'm very new to programming. I realize my bubble sort is wrong as well, I just don't know where to start fixing it...
I'd normally use std::sort with a comparison operator for each field you want to be able to compare. You can implement those either as named classes:
struct by_title {
bool operator()(Video const &a, Video const &b) {
return a.title < b.title;
}
};
struct by_rating {
bool operator()(Video const &a, Video const &b) {
return a.rating < b.rating;
}
};
// ...
std::sort(videos.begin(), videos.end(), by_rating);
std::sort(videos.begin(), videos.end(), by_title);
...or you can use a lambda expression to define a comparison:
// sort by rating
std::sort(videos.begin(), videos.end(), [](auto &a, auto &b) { return a.rating < b.rating; });
// sort by title
std::sort(videos.begin(), videos.end(), [](auto &a, auto &b) { return a.title < b.title; });

How to print students name in ascending according to marks

I had sort the mark for all tests, quizzes, assignments and final exam in ASCENDING order. But I don't know how to display all student's name in ascending order based on their mark for each tests, quizzes, assignments and final exam.
Below are my code to sort each mark for tests, quizzes, assignments and final exam in ascending order. How to change the code so that it will display the students name, not the marks for each tests, quizzes, assignments and final exam?
Please, help. Thank you in advance.
#include <iostream>
#include <string>
using namespace std;
//global constant
const int NUM_STUDENTS=5;//row
const int NUM_SCORES=4;//col
string name[5]={"Hani","Haziq","Aiman","Farah","Sabrina"};
string mark[4]={"test","quiz","assignment","final exam"};
//Function prototypes
void ascenDescen(double [ ][NUM_SCORES],int);
int main ( )
{
cout<<"This program will help you keep track of your academic record!"<<endl;
double scores[NUM_STUDENTS][NUM_SCORES]=
{{9.0,2.7,16.0,78.0},
{7.4,2.7,19.0,88.0},
{8.9,3.5,17.5,93.7},
{10.0,3.0,19.5,64.8},
{6.3,3.0,16.0,74.2}};
//function call
ascenDescen(scores,NUM_STUDENTS);
cout<<endl;
cout<<"THANK YOU."<<endl;
return 0;
}
void ascenDescen (double table[][NUM_SCORES],int rows)
{
//for ascending
cout<<"Press ENTER to sort the mark for all tests, quizzes, assignments and final exam in ASCENDING order : \n\n";
char ch;
ch=cin.get();
double ascen;
for(int col=0;col<NUM_SCORES;col++)
{
for(int row=0;row<NUM_STUDENTS;row++)
{
for(int j=row+1;j<NUM_STUDENTS;++j)
{
if(table[row][col]>table[j][col])
{
ascen=table[row][col];
table[row][col]=table[j][col];
table[j][col]=ascen;
}
}
}
cout<<mark[col]<<" mark in ASCENDING order : \n";
for(int row=0;row<NUM_STUDENTS;row++)
{
cout<<" ";
cout<<table[row][col];
cout<<endl;
}
}
cout<<"________________________"<<endl;
}
A rule of thumb: If you need parallel arrays, chances are you should have a vector of struct.
Let's try modeling the data using a Student structure:
struct Student
{
std::string name;
std::vector<int> marks;
};
Thus far, every Student has a name and has some marks. The has-a relationship indicates composition. The is-a relationship indicates inheritance.
Let's add a sort method for the marks. The students will be easier to order by marks, if the marks are sorted.
struct Student
{
//...
void sort_marks()
{
std::sort(marks.begin(), marks.end()); // Assume default of `std::less<int>`
}
};
To perform an ordering other than the default, we'll need to define a custom ordering function:
bool Order_By_Marks(const Student& a, const Student& b)
{
bool a_is_less_than_b = true;
unsigned int quantity_of_marks = a.marks.size();
if (b.marks.size() < quantity_of_marks)
{
quantity_of_marks = b.marks.size();
}
for (unsigned int i = 0; i < quantity_of_marks; ++i)
{
if (a.marks[i] > b.marks[i])
{
a_is_less_than_b = false;
break;
}
}
return a_is_less_than_b;
}
To sort a database of Student by marks:
std::vector<Student> database;
// ... input students ...
for (i = 0; i < database.size(); ++i)
{
database[i].sort_marks();
}
std::sort(database.begin(), database.end(), Order_By_Marks);
You'll need to walk through the code with a debugger to verify the ordering of the student marks and also the ordering of the students by mark.
#include <iostream>
#include <string>
using namespace std;
//global constant
const int NUM_STUDENTS=5;//row
const int NUM_SCORES=4;//col
string name[5]={"Hani","Haziq","Aiman","Farah","Sabrina"};
string mark[4]={"test","quiz","assignment","final exam"};
struct student {
};
//Function prototypes
void ascenDescen(double [ ][NUM_SCORES],int);
int main ( )
{
cout<<"This program will help you keep track of your academic record!"<<endl;
double scores[NUM_STUDENTS][NUM_SCORES]=
{{9.0,2.7,16.0,78.0},
{7.4,2.7,19.0,88.0},
{8.9,3.5,17.5,93.7},
{10.0,3.0,19.5,64.8},
{6.3,3.0,16.0,74.2}};
//function call
ascenDescen(scores,NUM_STUDENTS);
cout<<endl;
cout<<"THANK YOU."<<endl;
return 0;
}
void ascenDescen (double table[][NUM_SCORES],int rows)
{
//for ascending
cout<<"Press ENTER to sort the mark for all tests, quizzes, assignments and final exam in ASCENDING order : \n\n";
cin.get();
double ascen;
string temp1[5] = name;
string temp2;
for(int col=0;col<NUM_SCORES;col++)
{
for(int row=0;row<NUM_STUDENTS;row++)
{
for(int j=row+1;j<NUM_STUDENTS;++j)
{
if(table[row][col]>table[j][col])
{
ascen=table[row][col];
temp2 = temp1[row];
table[row][col]=table[j][col];
temp1[row] = temp1[j];
table[j][col]=ascen;
temp1[j] = temp2;
}
}
}
cout<<mark[col]<<" mark in ASCENDING order : \n";
for(int row=0;row<NUM_STUDENTS;row++)
{
cout<<" ";
cout << temp1[row] << " " <<table[row][col];
cout<<endl;
}
for(int i = 0; i < NUM_STUDENTS; i++)
{
temp1[i] = name[i];
}
}
cout<<"________________________"<<endl;
}

Student Results Management System in C++, expression must have pointer to object type

I was wondering if someone could help me fix this. I am looking to grab the lowest score in a student management results analysis project in C++. I am getting a "expression must have pointer to object type" error. I have no idea how to fix this
struct candidate
{
int candidates;
char forename[20], surname[20];
int area[5];
double avg;
public:
void getdata();
string calculateGrade();
void showdata() const;
};
//Prints out the lowest mark
void lowestmark(double avg[])
{
candidate st;
ifstream inFile;
inFile.open("student.dat", ios::binary);
if (!inFile)
{
cout << "File could not be open! Press any Key...";
cin.ignore();
cin.get();
return;
}
while (inFile.read(reinterpret_cast<char *> (&st), sizeof(candidate)))
{
double smallest = st.avg;
// Loop to determine lowest score
for (int i = 0; i < sizeof(candidate); i++)
{
if (smallest > st.avg[i])
{
smallest = st.avg[i];
smallest = i;
}
}
}
}
You don't need an array to find the smallest average score:
double smallest_average = 100000.0;
candidate st;
while (infile.read((unsigned char *) &st, sizeof(st)))
{
const double average_read = st.avg;
if (average_read < smallest_average)
{
smallest_average = average_read;
}
}
The search does not require all items stored into memory; only the current item read from the file.

Shopping List program: In VIM "Segmentation fault (core dumped)", but Codeblocks works [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hope your day is going well.
I am a bit of a noobie when it comes to programming so please bear with me. I have two problems. I am attempting to create a program consisting of 5 files: items.h, items.cpp, list.h, list.cpp, and main. There is an Item class and a List class. The object of this program is to create a shopping list that allows the user to enter an Item Name, the Item Unit, cost per Unit, and then add it to the list. The program also allows you to remove an item by its name. We cannot use vectors.
Problem 1: What I have so far will run in Codeblocks, but when I run it in VIM, I get the error "Segmentation fault (core dumped)."
Problem 2: I also come across an error when I attempt to add another variable to use in main, such as amountToBuy (contains the int number of Items user wants to buy)--when added, the program in Codeblocks won't run, stating "std::bad_alloc". I've commented some things out so the program will run.
I am at a complete loss and don't know which lines are causing the issues or how I would go about fixing things. Any input would be greatly appreciated. Thank you very much!
list.h
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
#include "items.h"
#include <string>
class List
{
private:
int arrayPosition;
int arraySize;
Item* itemsOnList = new Item[arraySize];
public:
List();
void addItem(Item);
void removeItem(std::string ri);
void displayList();
};
#endif // LIST_H_INCLUDED
list.cpp
#include "list.h"
#include "items.h"
#include <string>
#include <iostream>
/*******************************************************************
List::List()
Constructor initializes List size to 4 as default
*******************************************************************/
List::List()
{
arraySize = 4;
arrayPosition = 0;
}
/*******************************************************************
void List::addItem(Item)
This function adds the specified Item to the List
*******************************************************************/
void List::addItem(Item i)
{
//x2 arraySize when arrayPosition gets too close to arraySize
if (arrayPosition == arraySize)
{
//doubling arraySize since we need more space
arraySize *= 2;
//tempList to hold the old List's items
Item* tempList = new Item[arraySize];
//transferring information to tempList
for (int a = 0; a < arrayPosition; a++)
{
tempList[a] = itemsOnList[a];
}
delete[] itemsOnList;
//transferring data from temp List back to Old list
itemsOnList = tempList;
delete[] tempList;
//adding next item to list
itemsOnList[arrayPosition++] = i;
}
else
{
//adding next item to list
itemsOnList[arrayPosition++] = i;
}
}
/*******************************************************************
void List::removeItem(std::string)
This function removes the specified Item to the List
*******************************************************************/
void List::removeItem(std::string ri)
{
for (int a = 0; a < arrayPosition; a++)
{
if (itemsOnList[a].getItemName() == ri)
{
//moving the rest of the items down one position
//to take the removed item's spot
for (int b = a; b < arrayPosition; b++)
{
itemsOnList[b] = itemsOnList[b+1];
}
//decreasing arrayPosition by one because Item was removed
--arrayPosition;
}
}
}
/*******************************************************************
void List::displayList()
This function displays the List
*******************************************************************/
void List::displayList()
{
std::cout << "The following Items are on your Grocery List\n\n";
for (int i = 0; i < arrayPosition; i++)
{
std::cout << "Item name: " << itemsOnList[i].getItemName() << std::endl;
//std::cout << "Number to buy: " << itemsOnList[i].getNumberToBuy() << std::endl;
}
std::cout << std::endl;
}
items.h
#ifndef ITEMS_H_INCLUDED
#define ITEMS_H_INCLUDED
#include <string>
class Item
{
private:
std::string itemName;
//int numberToBuy;
public:
Item();
Item(std::string);
//setters
void setItemName(std::string);
//void setNumberToBuy(int);
//getters
std::string getItemName();
};
#endif // ITEMS_H_INCLUDED
items.cpp
#include "items.h"
Item::Item()
{
itemName = "empty";
//numberToBuy = 0;
}
//this constructor accepts a string and an int
Item::Item(std::string in)
{
itemName = in;
//numberToBuy = ntb;
}
//setters
void Item::setItemName(std::string in)
{
itemName = in;
}
/*
void Item::setNumberToBuy(int ntb)
{
numberToBuy = ntb;
}
*/
//getters
std::string Item::getItemName()
{
return itemName;
}
main.cpp
#include "list.h"
#include "items.h"
#include <iostream>
int main()
{
int menuChoice, subMenuChoice;
std::string itemName, removeItem;
bool exit = false;
List newList;
//introduction
std::cout << "Welcome to your Grocery List!\n\n";
do
{
//menu
std::cout << "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \n\n";
std::cout << "To select a menu item, please select its corresponding number.\n\n";
//menu prompts and storing the choice
std::cout << "1. Add items to Grocery List\n";
std::cout << "2. Remove items from Grocery List\n";
std::cout << "3. Display Grocery List\n";
std::cout << "4. Exit\n\n";
std::cout << "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \n\n";
std::cout << "Menu choice: ";
std::cin >> menuChoice;
std::cout << std::endl;
//menu choice break-away section
if (menuChoice == 1)
{
do
{
std::cout << "Please enter the name of the item: ";
std::cin >> itemName;
//std::cout << "Please enter the unit (cans, lbs, oz): ";
//std::cin >> itemUnit;
//std::cout << "Please enter number to buy: ";
//std::cin >> amountToBuy;
Item theItem(itemName);
newList.addItem(theItem);
std::cout << "Would you like to add another item? For YES type 1 | For NO type 0: ";
std::cin >> subMenuChoice;
std::cout << std::endl;
}
while(subMenuChoice == 1);
}
else if (menuChoice == 2)
{
std::cout << "Please enter the name of the item you want to remove: ";
std::cin >> removeItem;
std::cout << std::endl;
newList.removeItem(removeItem);
}
else if (menuChoice == 3)
{
newList.displayList();
}
else if (menuChoice == 4)
{
exit = true;
std::cout << "Goodbye!" << std::endl;
}
}
while (exit == false);
return 0;
}
In
class List
{
private:
int arrayPosition;
int arraySize;
Item* itemsOnList = new Item[arraySize];
public:
List();
void addItem(Item);
void removeItem(std::string ri);
void displayList();
};
Item* itemsOnList = new Item[arraySize]; will execute before the body of the constructor so by the time
List::List()
{
arraySize = 4;
arrayPosition = 0;
}
runs and arraySize is set to 4, itemsOnList has already been assigned an array of unknown size or the program has crashed.
A simple fix for this is
class List
{
private:
int arrayPosition;
int arraySize;
Item* itemsOnList;
public:
List();
void addItem(Item);
void removeItem(std::string ri);
void displayList();
};
and
List::List()
{
arraySize = 4;
arrayPosition = 0;
itemsOnList = new Item[arraySize]
}
or
List::List():
arrayPosition(0),
arraySize(4),
itemsOnList(new Item[arraySize])
{
}
The second uses the unfortunately under-taught Member Initializer List. This is often the best approach because it ensures that the object is fully constructed before entering the body of the constructor. For complex objects this prevents having to redo any work performed by default constructors that are used to make certain the object is valid before use.
Edit: A note on the Member Initializer List link above. The first third might look as though written in Martian. Skip down to the Explanation section and start reading there, then go back up to the specifics, if needed.
In addItem the following will also cause problems:
Item* tempList = new Item[arraySize]; //created new array
//transferring information to tempList
for (int a = 0; a < arrayPosition; a++)
{
tempList[a] = itemsOnList[a]; //copying old to new
}
delete[] itemsOnList; //free old list storage
//transferring data from temp List back to Old list
itemsOnList = tempList; // assign new list to old list
delete[] tempList; // whoops. Freed new list storage
For a brief period of time tempList and itemsOnList point to the same storage, so deleteing either pointer will free the storage for both. Solution: Don't delete[] tempList;
In RemoveItem:
for (int b = a; b < arrayPosition; b++)
{
itemsOnList[b] = itemsOnList[b+1];
}
b can range up to arrayPosition - 1, so itemsOnList[b+1] can be written as itemsOnList[arrayPosition-1+1] or as itemsOnList[arrayPosition]. arrayPosition may be one past the end of the end of the list if the list was full.
Your code has three stand-out issues.
No initialization of 'arraySize' and 'arrayPosition'.
You don't specify an initial value for 'arraySize' but you do specify
Item* itemsOnList = new Item[arraySize];
Because of the way you have specified this, at best it will always produce a zero-length (nullptr) itemsOnList, at worst it will use some uninitialized and thus random value to create a randomly sized array, and arrayPosition will also be randomly smaller or larger than the arraySize value.
size *= 2
if (arrayPosition == arraySize)
{
//doubling arraySize since we need more space
arraySize *= 2;
In the best-case scenario, your arraySize starts as zero. Thus when you double it, you get: zero.
Deletion of everything.
In addItem, you do the following:
delete[] itemsOnList;
//transferring data from temp List back to Old list
itemsOnList = tempList;
at this point, both itemsOnList and tempList point to the same array. So the next statement:
delete[] tempList;
deletes your second copy - now both the old and new arrays are deleted.

Declaring my member function parameters/arguments

class Seller
{
private:
float salestotal; // run total of sales in dollars
int lapTopSold; // running total of lap top computers sold
int deskTopSold; // running total of desk top computers sold
int tabletSold; // running total of tablet computers sold
string name; // name of the seller
Seller::Seller(string newname)
{
name = newname;
salestotal = 0.0;
lapTopSold = 0;
deskTopSold = 0;
tabletSold = 0;
}
bool Seller::SellerHasName ( string nameToSearch )
{
if(name == nameToSearch)
return true;
else
return false;
}
class SellerList
{
private:
int num; // current number of salespeople in the list
Seller salespeople[MAX_SELLERS];
public:
// default constructor to make an empty list
SellerList()
{
num = 0;
}
// member functions
// If a salesperson with thisname is in the SellerList, this
// function returns the associated index; otherwise, return NOT_FOUND.
// Params: in
int Find ( string thisName );
void Add(string sellerName);
void Output(string sellerName);
};
int SellerList::Find(string thisName)
{
for(int i = 0; i < MAX_SELLERS; i++)
if(salespeople[i].SellerHasName(thisName))
return i;
return NOT_FOUND;
}
// Add a salesperson to the salespeople list IF the list is not full
// and if the list doesn't already contain the same name.
void SellerList::Add(string sellerName)
{
Seller(sellerName);
num++;
}
I have some issues with the parameters in my functions in my SellerList class. I want to add someone to the salespeople array so I have a record of all my sellers... Bob, Pam, Tim, etc... My constructor Seller(sellerName) creates a Seller with name sellerName.
How do I add this Seller to the Salespeople array and have capability of a way to pull the data back out and use it in more functions such as a Update function, or an output function?
MAX_SELLERS = 10.... I guess my issue is not knowing whether to use parameters of only
Add(string) or Add(Seller, string). Any help would be appreciated.
Not reinvent the wheel. Choose the container appropiate to your problem. In this case, because you are referencing/searching Sellers by a std::string, I suggest you to use a hash table like std::unordered_map (Or std::map search tree if you don't have access to C++11):
int main()
{
std::unordered_map<Seller> sellers;
//Add example:
sellers["seller name string here"] = /* put a seller here */;
//Search example:
std::unordered_map<Seller>::iterator it_result = sellers.find( "seller name string here" );
if( it_result != std::end( sellers ) )
std::cout << "Seller found!" << std::endl;
else
std::cout << "Seller not found :(" << std::endl;
}
How about using STD vector inside of SellerList instead of the array.
vector<Seller> x;
you can do x.push_back(Seller(...)) or x[0].SellerHasName() and x.size() will give you the number of sellers.
maybe something like this?
// Add a salesperson to the salespeople list IF the list is not full
// and if the list doesn't already contain the same name.
void SellerList::Add(string sellerName)
{
if(num < MAX_SELLERS)
salespeople[num++] = new Seller(sellerName);
}