Sorting (Vector of Objects) - c++

I'm a new programmer in C++ and I'm stuck with a problem:
I have this class:
class car{
public:
//Default Constructor
car();
//Overload Constructor
car(string, int, float, float);
//Desctructor
~car();
//Access Functions
string getbrand() const;
int getyear() const;
float getkm() const;
float getprice() const;
//Mutator Functions
void setbrand(string);
void setyear(int);
void setkm(float);
void setprice(float);
private:
//variables
string newbrand;
int newyear;
float newkm;
float newprice;
};
//Access Functions
string car::getbrand() const{
return newbrand;
}
int car::getyear() const{
return newyear;
}
float car::getkm() const{
return newkm;
}
float car::getprice() const{
return newprice;
}
So, once I've started to insert my cars I've put them in a vector:
void fillvector(vector<car>& newmyfleet){
string brand;
int year;
float km;
float price;
cout << "How many cars do you want in your fleet? ";
int fleetsize;
cin >> fleetsize;
for (int i = 0; i < fleetsize; i++){
cout << "Car Brand: ";
cin >> brand;
cout << "Car Year: ";
cin >> year;
cout << "Car Kms: ";
cin >> km;
cout << "Car Price: ";
cin >> price;
car newcar(brand, year, km, price);
newmyfleet.push_back(newcar);
cout << endl;
}
cout << endl;
}
So my question is this: How can I sort all my cars, from the vector, by brand?!!
I've tried using sort but I cannot...
This was my last solution:
//function 1
bool sortbybrand(car &c1, car &c2) { return c1.getbrand() < c2.getbrand(); }
//sorting
void sbrand(const vector<car>& newmyfleet){
unsigned int size = newmyfleet.size(); //Number of cars
sort(newmyfleet.begin(), newmyfleet.end(), sortbybrand);
cout << "Sorting Cars by Brand\n\n " << endl;
for (unsigned int i = 0; i < size; i++){
cout << "Car: " << i + 1 << endl;
cout << "Car Brand: " << newmyfleet[i].getbrand() << endl;
cout << "Car Year: " << newmyfleet[i].getyear() << endl;
cout << "Car Kms: " << newmyfleet[i].getkm() << endl;
cout << "Car Price: " << newmyfleet[i].getprice() << endl;
cout << endl;
}
}

Related

collect2: error: ld returned 1 exit status undefined references

This is my code for an online shopping cart containing two items.
I'm getting the following linker error.
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\chine\AppData\Local\Temp\ccQnOWnO.o:main.cpp:(.text+0x121): undefined reference to `ItemToPurchase::SetPrice(int)
I get similar errors to all my functions in my public class. I double-checked all my parameters and made sure they had the matching data types and made sure I'd defined my functions. Here is my code. I'm fairly new to C++ so I'm just looking to learn and make sure this doesn't happen again.
ItemToPurchase.cpp
#include "ItemToPurchase.h"
ItemToPurchase::ItemToPurchase() {
string itemName = "none";
int itemPrice = 0;
int itemQuantity = 0;
}
string ItemToPurchase::GetName() {
return itemName;
}
int ItemToPurchase::GetPrice() {
return itemPrice;
}
int ItemToPurchase::GetQuantity() {
return itemQuantity;
}
void ItemToPurchase::SetName(const char* itemName) {
this->itemName = itemName;
}
void ItemToPurchase::SetPrice(int price) {
itemPrice = price;
}
void ItemToPurchase::SetQuantity(int quantity) {
itemQuantity = quantity;
}
main.c
#include "ItemToPurchase.h"
int main() {
ItemToPurchase Item1;
ItemToPurchase Item2;
string item1name;
int item1price;
int item1quantity;
string item2name;
int item2price;
int item2quantity;
cout << "Item 1";
cout << "Enter the item name: ";
getline(cin, item1name);
item1name = Item1.GetName();
Item1.SetName(item1name.c_str());
cout << "Enter the item price: ";
cin >> item1price;
item1price = Item1.GetPrice();
Item1.SetPrice(item1price);
cout << "Enter the item quantity: ";
cin >> item1quantity;
item1quantity = Item1.GetQuantity();
Item1.SetQuantity(item1quantity);
cout << "Item 2";
cout << "Enter the item name: ";
getline(cin, item2name);
item2name = Item2.GetName();
Item2.SetName(item2name.c_str());
cout << "Enter the item price: ";
cin >> item2price;
item2price = Item2.GetPrice();
Item2.SetPrice(item2price);
cout << "Enter the item quantity: ";
cin >> item2quantity;
item2quantity = Item2.GetQuantity();
Item2.SetQuantity(item2quantity);
cout << "TOTAL COST" << endl;
cout << item1name << item1quantity << "# " << "$" << item1price << "= " << "$" << item1price * item1quantity << endl;
cout << item2name << item2quantity << "# " << "$" << item2price << "= " << "$" << item2price * item2quantity << endl;
cout << "TOTAL: " << "$" << (item1price * item1quantity) + (item2price * item2quantity) << endl;
return 0;
}
header file
#include <string>
#include <iostream>
using namespace std;
class ItemToPurchase {
public:
ItemToPurchase();
string GetName();
int GetPrice();
int GetQuantity();
void SetName(const char* itemName);
void SetPrice(int price);
void SetQuantity(int quantity);
private:
string itemName;
int itemPrice;
int itemQuantity;
};
#endif
Make sure SetPrice(int price) is defined in class ItemToPurchase in ItemToPurchase.h.

C++ Virtual Void

Okay, so I have a parent class called employee and 3 subclass called manager,researcher and engineer. I made a vector and want to list them. this is the how I process the making.
vector <Employee*,Manager*> EmployeeDB;
Employee *temp;
temp = new Manager(first, last, salary, meetings, vacations);
EmployeeDB.push_back(temp);
I have no problem in making the vector, my concern is listing the info. all 3 subclasses have firstname, lastname and salary but they're difference is that they have different data members which is unique, example the Manager has the int value vacation and the Engineer has the int value experience so on and so forth.
Employee.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef EMPLOYEE_h
#define EMPLOYEE_h
class Employee
{
public:
Employee();
Employee(string firstname, string lastname, int salary);
string getFname();
string getLname();
int getSalary();
virtual void getInfo();
private:
string mFirstName;
string mLastName;
int mSalary;
};
#endif
Employee.cpp:
#include "Employee.h"
#include <iostream>
#include <string>
using namespace std;
Employee::Employee()
{
mFirstName = "";
mLastName = "";
mSalary = 0;
}
Employee::Employee(string firstname, string lastname, int salary)
{
mFirstName = firstname;
mLastName = lastname;
mSalary = salary;
}
string Employee::getFname()
{
return mFirstName;
}
string Employee::getLname()
{
return mLastName;
}
int Employee::getSalary()
{
return mSalary;
}
void Employee::getInfo()
{
cout << "Employee First Name: " << mFirstName << endl;
cout << "Employee Last Name: " << mLastName << endl;
cout << "Employee Salary: " << mSalary << endl;
}
Main:
#include <vector>
#include <iostream>
#include <string>
#include "Employee.h"
#include "Engineer.h"
#include "Manager.h"
#include "Researcher.h"
using namespace std;
vector <Employee*> EmployeeDB;
Employee *temp;
void add()
{
int emp, salary, vacations, meetings, exp, c;
string first, last, type, school, topic;
bool skills;
do
{
system("cls");
cout << "===========================================" << endl;
cout << " Add Employee " << endl;
cout << "===========================================" << endl;
cout << "[1] Manager." << endl;
cout << "[2] Engineer." << endl;
cout << "[3] Researcher." << endl;
cout << "Input choice: ";
cin >> emp;
system("cls");
} while (emp <= 0 || emp > 3);
cout << "===========================================" << endl;
cout << " Employee Info " << endl;
cout << "===========================================" << endl;
cout << "Employee First name: ";
cin >> first;
cout << "Employee Last name: ";
cin >> last;
cout << "Employee Salary: ";
cin >> salary;
switch (emp)
{
case 1:
cout << "Employee numbers of meetings: ";
cin >> meetings;
cout << "Employee numbers of vacations: ";
cin >> vacations;
temp = new Manager(first, last, salary, meetings,vacations);
EmployeeDB.push_back(temp);
delete temp;
break;
case 2:
cout << endl;
cout << "[1]YES [2]NO" << endl;
cout << "Employee C++ Skills: ";
cin >> c;
if (c == 1)
{
skills = true;
}
else
{
skills = false;
}
cout << "Employee Years of exp: ";
cin >> exp;
cout << "(e.g., Mechanical, Electric, Software.)" << endl;
cout << "Employee Engineer type: ";
cin >> type;
temp = new Engineer(first, last, salary, skills, exp, type);
EmployeeDB.push_back(temp);
delete temp;
break;
case 3:
cout << "Employee School where he/she got his/her PhD: ";
cin >> school;
cout << "Employee Thesis Topic: ";
cin >> topic;
temp = new Researcher(first, last, salary, school, topic);
EmployeeDB.push_back(temp);
delete temp;
break;
}
}
void del()
{
}
void view()
{
for (int x = 0; x < (EmployeeDB.size()); x++)
{
cout << EmployeeDB[x]->getInfo();
}
}
void startup()
{
cout << "===========================================" << endl;
cout << " Employee Database " << endl;
cout << "===========================================" << endl;
cout << "[1] Add Employee." << endl;
cout << "[2] Delete Employee." << endl;
cout << "[3] List Employees." << endl;
cout << "[4] Exit." << endl;
cout << "Please Enter Your Choice: ";
}
int main(int argc, char** argv)
{
bool flag = true;
int choice;
do {
do
{
system("cls");
system("pause>nul");
startup();
cin >> choice;
} while (choice < 0 || choice >4);
switch (choice)
{
case 1:
add();
break;
case 2:
del();
break;
case 3:
view();
break;
case 4:
flag = false;
system("EXIT");
break;
}
} while (flag == true);
return 0;
system("pause>nul");
}
I am getting error on the view() function.
It says no operator<< matches these operands
binary '<<': no operator found which takes a right hand operand of type void etc etc.
The problem is that the getInfo has return type void and you are trying to put that return value into cout.
It's important to understand that the code std::cout << val actually calls the function operator<<(ostream& out, const objectType& val) where objectType is the type of 'val'.
In your case the type is void, and there is simply no implementation of operator<< that takes void as a type. hence the error "no operator found which takes a right hand operand of type void...".
In order to fix your issue you have a few options:
Change view() to be
for (...)
{
EmployeeDB[x]->getInfo();
}
Change getInfo() to return a string the info as you'd like:
std::string getInfo()
{
std::string info;
info =...
return info;
}
Create an operator<< for Employee and change view to call it:
view()
{
for (...)
{
std::cout << EmployeeDB[x];
}
}

Working with classes and cant get my output to work

I'm finishing a project with a class and will have to have it output my information. I keep getting an error with line 33 saying 'Human : undeclared identifier'.
Here is my full program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int height;
int weight;
int age;
string name;
cout << "Please enter your name: ";
cin >> name;
cin.clear();
cout << endl;
cout << "Please enter your height (in inches): ";
cin >> height;
cin.clear();
cout << endl;
cout << "Please enter your weight (in whole pounds): ";
cin >> weight;
cin.clear();
cout << endl;
cout << "Please enter your age (in whole years): ";
cin >> age;
cin.clear();
cout << endl;
Human myHuman;
myHuman.editHeight(height);
myHuman.editAge(age);
myHuman.editWeight(weight);
myHuman.editName(name);
cout << "Your description: ";
cout << endl;
myHuman.outputDescription();
return 0;
}
class Human
{
public:
Human();
int getAge();
void editAge(int a);
int getHeight();
void editHeight(int h);
int getWeight();
void editWeight(int w);
string getName();
void editName(string in);
void outputDescription();
private:
int m_age;
int m_height;
int m_weight;
string m_name;
};
string Human::getName()
{
return m_name;
}
void Human::editName(string in)
{
m_name = in;
}
int Human::getAge()
{
return m_age;
}
void Human::editAge(int a)
{
m_age = a;
}
int Human::getHeight()
{
return m_height;
}
void Human::editHeight(int h)
{
m_height = h;
}
int Human::getWeight()
{
return m_weight;
}
void Human::editWeight(int w)
{
m_weight = w;
}
void Human::outputDescription()
{
cout << "Hello " << m_name << " you are " << m_height << " inches tall and weigh " << m_weight
<< " pounds, and are currently " << m_age << " years old.";
}
If anyone could shine some light on this for me, that would be great. I appreciate the help!

How to add a name field for a shop database (OOP/C++)

Ok, so I've made a database type program and created an item number and price field. I've also tried to stick to a primary key by using the index values of the array of both the "item number" field and "price". But was wondering how to add an "Item name" field along with this to make it work. I've tried to think of many different ways of adding a char type array but that doesn't really work.
#include<iostream>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the price of the item: ";
cin >> price[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Price: " << price[i] << endl << endl;
}
}
void main()
{
class shop s;
s.input();
s.output();
}
Create a class or struct to hold the data:
struct Item
{
int id;
float price; // float may lead to rounding errors.
// I would use int and store cents
//string name;
// If you really want to use c-style string
char name[20];
// or
// char *name; // You would need to use new with this
};
Then keep an array of these:
class shop
{
private:
Item items[20];
// As mentioned, better than a static array would be a vector
//std::vector<Item> items;
public:
void input();
void output();
};
What about a vector of strings?
#include<iostream>
#include <string>
#include <vector>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
vector<string> names;
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
names.resize(n);
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the price of the item: ";
cin >> price[i];
cout << "Enter the name of the item: ";
cin >> names[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Price: " << price[i] << endl << endl;
cout << "Name: " << names[i] << endl << endl;
}
}
And it would be good to have a destructor to clean the memory taken by the vector.
I would use std::string
#include <iostream>
#include <string>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
string name[20];
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the name of the item: ";
cin >> name[i];
cout << "Enter the price of the item: ";
cin >> price[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Item Name: " << name[i] << endl;
cout << "Price: " << price[i] << endl << endl;
}
}
int main()
{
class shop s;
s.input();
s.output();
}

Error LNK2019 - Unsure how to fix (1 unresolved external) [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 9 years ago.
I am nearly done with this program, however I am getting an error that I am unsure how to deal with. I have looked for other solutions but none have seemed to help
The error I'm getting is:
error LNK2019: unresolved external symbol "void __cdecl deposit(class customer * const,int)" (?deposit##YAXQAVcustomer##H#Z) referenced in function _main
C:\Users\D\Desktop\Programs\Project 3\DProject3\Debug\DProject3.exe : fatal error LNK1120: 1 unresolved externals
It seems to have something to do with the deposit function, however I have tried fooling around with it to no avail, if anyone could help it would be much appreciated, I have 3 files for this project
Header
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include <string>
struct Date
{
int Day;
int Month;
int Year;
};
struct Name
{
std::string first_name;
std::string middle_name;
std::string last_name;
};
class customer
{
private:
Date birth_date;
Name name;
float balance_saving, balance_checking, initial_saving, initial_checking, amount, account_type;
public:
customer(); //Customer constructor
customer(Date birth_date, Name name, float initial_saving, float initial_checking); // Customer constructor with info
void withdraw(float amount, int account_type);
void deposit(float amount, int account_type);
float check_balance_saving(); // Print out the savings balance on screen
float check_balance_checking(); // Print out the checking balance on screen
void setDate(int Day, int Month, int Year);
Date getDate();
void setName(std::string first_name, std::string middle_name, std::string last_name);
Name getName();
void setSaving(float initial_saving);
void setChecking(float initial_checking);
};
#endif
Implementation File
#include "customer.h"
//Contructor without info / Default info
customer::customer()
{
birth_date.Day = 01;
birth_date.Month = 01;
birth_date.Year = 1901;
name.first_name = "N/A";
name.middle_name = "N/A";
name.last_name = "N/A";
balance_saving = 0;
balance_checking = 0;
}
// Constructor with user input data
customer::customer(Date DMY, Name FML, float initSav, float initCheck)
{
birth_date = DMY;
name = FML;
initial_saving = initSav;
initial_checking = initCheck;
}
void customer::withdraw(float amtW, int accW)
{
amount = amtW;
account_type = accW;
}
void customer::deposit(float amtD, int accD)
{
amount = amtD;
account_type = accD;
}
float customer::check_balance_saving()
{
return initial_checking;
}
float customer::check_balance_checking()
{
return initial_checking;
}
void customer::setDate(int Day, int Month, int Year)
{
birth_date.Day = Day;
birth_date.Month = Month;
birth_date.Year = Year;
}
Date customer::getDate()
{
return birth_date;
}
void customer::setName(std::string First, std::string Middle, std::string Last)
{
name.first_name = First;
name.middle_name = Middle;
name.last_name = Last;
}
Name customer::getName()
{
return name;
}
void customer::setSaving(float setSav)
{
initial_saving = setSav;
}
void customer::setChecking(float setCheck)
{
initial_checking = setCheck;
}
Main
#include "customer.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
//Function prototypes
void withdraw (customer[], int);
void deposit (customer[], int);
void checkBal (customer[], int);
void newAccountFile (customer[], int);
int main ()
{
customer custInfo[49]; //Creates the customer array for info to be stored in
int customerAmt = 0; //Keeps track of the amount of customers in the array
ifstream customerfile ("account.dat"); //Open existing customer file
while (customerAmt < 2) //Loop to read the data from the existing file
{
int D, M, Y; // Birth day, month, year
string FN, MN, LN; //First name, middle name, last name
float Save, Check; //Savings & Checking initial amount
customerfile >> D;
customerfile >> M;
customerfile >> Y;
customerfile >> FN;
customerfile >> MN;
customerfile >> LN;
customerfile >> Save;
customerfile >> Check;
custInfo[customerAmt].setDate(D, M, Y);
custInfo[customerAmt].setName(FN, MN, LN);
custInfo[customerAmt].setSaving(Save);
custInfo[customerAmt].setChecking(Check);
customerAmt++;
}
customerfile.close(); //Close customer file and end file reading
//Variables for the User menu
int accountNumber, option, D1, M1, Y1;
string FN1, MN1, LN1;
float Save1, Check1;
//Loop used for User menu
do
{
cout << "1. withdraw" << endl;
cout << endl;
cout << "2. Deposit" << endl;
cout << endl;
cout << "3. Check Balances" << endl;
cout << endl;
cout << "4. Create a New Account" << endl;
cout << endl;
cout << "0. Exit" << endl;
cin >> option;
if (option == 1) // Uses withdraw function
{
cout << "Enter the account number: ";
cin >> accountNumber;
withdraw(custInfo, accountNumber);
}
else if (option == 2) // Uses deposit function
{
cout << "Enter the account number: " << endl;
cin >> accountNumber;
deposit(custInfo, accountNumber);
}
else if (option == 3) // Uses check balance function
{
cout << "Enter the account number: " << endl;
cin >> accountNumber;
checkBal(custInfo, accountNumber);
}
else if (option == 4) //Option to handle creating a new account
{
cout << "Enter the new account information, starting with birth info: " << endl;
cin >> D1 >> M1 >> Y1;
custInfo[customerAmt].setDate(D1, M1, Y1);
cout << endl;
cout << "Enter the new customer's full name: " << endl;
cin >> FN1 >> MN1 >> LN1;
custInfo[customerAmt].setName(FN1, MN1, LN1);
cout << endl;
cout << "Enter the inital savings balance: " << endl;
cin >> Save1;
custInfo[customerAmt].setSaving(Save1);
cout << endl;
cout << "Enter the initial checking balance: " << endl;
cin >> Check1;
custInfo[customerAmt].setChecking(Check1);
customerAmt++;
}
}while (option != 0);
newAccountFile(custInfo, customerAmt); // Creates new updated account info file
system ("pause");
return 0;
}
void withdraw(customer custInfo[], int number)
{
float withdrawAmount;
int optionWit;
float tempSave;
float tempCheck;
cout << "1. Withdraw from savings" << endl;
cout << endl;
cout << "2. Withdraw from checking" << endl;
cin >> optionWit;
cout << "Enter the amount to be withdrawn: ";
cin >> withdrawAmount;
if (optionWit == 1)
{
tempSave = custInfo[number].check_balance_saving() - withdrawAmount;
custInfo[number].setSaving(tempSave);
}
else if (optionWit == 2)
{
tempCheck = custInfo[number].check_balance_checking() - withdrawAmount;
custInfo[number].setChecking(tempCheck);
}
}
void desposit(customer custInfo[], int number)
{
float depositAmount;
int optionDep;
float tempSave;
float tempCheck;
cout << "1. Deposit to savings" << endl;
cout << endl;
cout << "2. Deposit to checking" << endl;
cin >> optionDep;
cout << "Enter the amount to be deposited: ";
cin >> depositAmount;
if (optionDep == 1)
{
tempSave = custInfo[number].check_balance_saving() + depositAmount;
custInfo[number].setSaving(tempSave);
}
else if (optionDep == 2)
{
tempCheck = custInfo[number].check_balance_checking() + depositAmount;
custInfo[number].setChecking(tempCheck);
}
}
void checkBal(customer custInfo[], int number)
{
int optionBal;
cout << "1. Check savings balance" << endl;
cout << endl;
cout << "2. Check checking balance" << endl;
cin >> optionBal;
if (optionBal == 1)
{
cout << "Current savings balance is: " << custInfo[number].check_balance_saving() << endl;
}
else if (optionBal == 2)
{
cout << "Current checking balance is: " << custInfo[number].check_balance_checking() << endl;
}
}
void newAccountFile(customer custInfo[], int size)
{
int i;
Date tempDate;
Name tempName;
ofstream newAccountStorage;
newAccountStorage.open ("updated_account.dat"); //Opens new file for updated account info
for (i = 0; i < size; i++);
{
tempDate = custInfo[i].getDate();
tempName = custInfo[i].getName();
newAccountStorage << tempDate.Day << endl;
newAccountStorage << tempDate.Month << endl;
newAccountStorage << tempDate.Year << endl;
newAccountStorage << tempName.first_name << endl;
newAccountStorage << tempName.middle_name << endl;
newAccountStorage << tempName.last_name << endl;
newAccountStorage << custInfo[i].check_balance_saving() << endl;
newAccountStorage << custInfo[i].check_balance_checking() << endl;
}
newAccountStorage.close(); //Closes the file after writing new information
}
You have misprint in your function definition
void desposit(customer custInfo[], int number)
^^^^