Printing an object after putting it into a map [closed] - c++

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 3 years ago.
Improve this question
class Task
{
public:
string study;
int time;
bool made;
int priority;
}
class Day
{
public:
string date = "undefined";
int aims = 0;
vector <Task> tasks;
}
i have 2 classes,where i use vector to keep data from both.
this project is a daily planner for one day.
Now i need to improve it to store more days,tutor wants me to use MAP.
map<string, Day>Days;
map<string, Day>::iterator it;
Days.insert(pair<string, Day>(s, d));
for (it = Days.begin(); it != Days.end(); ++it)
{
cout << it->first << " " << it->second << '\n';
}
E0349 missing operator "<<" corresponding to these operands
C2679 binary "<<": no operator was found that accepts a right operand of type "_Ty2" (or there is no acceptable conversion)
with
[_Ty2 = Day]
how can I do this?
void PrintDay(const Day& d, ChangeF Pd)
{
cout << "Current date:" << d.date << endl << "\n=============================================" << endl << "Number of tasks:" << d.aims;
cout << "\n=============================================" << endl;
for (int i = 0; i < d.aims; i++)
{
PrintTask(d.tasks[i], Pd);
}
}
Day InputDay()
{
setlocale(LC_ALL, "Russian");
Day d;
cout << "\nEnter date dd ENTER mm ENTER yyyy ENTER obe by one" << endl;
int dd, mm, yyyy;
dd = DigitInputCheck(1, 30);
mm = DigitInputCheck(1, 12);
yyyy = DigitInputCheck(0, 4000);
ostringstream WriteDate;
WriteDate << dd << "." << mm << "." << yyyy << endl;
d.date = WriteDate.str();
cout << "Number of tasks:" << endl;
cin >> d.aims;
for (int i = 0; i < d.aims; i++)
{
d.tasks.push_back(InputTask());
}
return d;
}

As mentioned in the comments, you need to overload the operator<< for the type Day if you are going to try to use << with it. Since you already have a PrintDay, I'll adapt it to work with the operator. I have no idea what Pd is supposed to be, so I'm ignoring it. This function should be a global function. Since all your fields are public, it doesn't need special access via friend either.
std::ostream &operator<<( std::ostream &os, const Day &day ) {
os << "Current date:" << d.date << '\n'
<< "\n=============================================\n"
<< "Number of tasks:" << d.aims
<< "\n=============================================\n";
for (int i = 0; i < d.aims; i++)
{
os << d.tasks[i];
}
}
You would also need to add the operator for your Task type as well. Given the above, you should be able to make another function for your PrintTask function.

Related

How do I display all the information of a class? [duplicate]

This question already has answers here:
How can I use cout << myclass
(5 answers)
Closed 2 years ago.
I just started coding so sorry if the code is too convoluded or messy, any tips are preciated
#include <iostream>
using namespace std;
class Nacion {
public:
string nombre;
string tematica;
string entorno;
Nacion (string aNombre , string aTematica , string aEntorno){
nombre = aNombre;
tematica = aTematica;
entorno = aEntorno;
}
};
int main(){
int eligNac;
string Categoria;
string Naciones;
Nacion nacion1 ("nombre" , "tematica" , "entorno");
Nacion nacion2 ("nombre" , "tematica" , "entorno");
Nacion nacion3 ("nombre" , "tematica" , "entorno");
cout << "Elije una categoria:\n";
cout << "Naciones\n";
cout << "Campeones" << endl;
cin >> Categoria;
if (Categoria == "Naciones")
{
cout << "Elije una naciĆ³n:\n";
cout << "1.-Demacia\n";
cout << "2.-Freldjord\n";
cout << "3.-Piltover\n" << endl;
cin >> eligNac >> endl;
if(eligNac = 1){
cout << nacion1 << endl;
}
}
This is the one line of code I have troubles with, I don't know how to display the info of the object when an imput is given
Your probably want to look into C++ operator overloading: https://en.cppreference.com/w/cpp/language/operators , specifically, the operator<< part.
In your case, you probably want to do something like:
std::ostream & operator<<(std::ostream & os, const Nacion & n) {
os << n.nombre << " / " << n.tematica << " / " << n.entorno << std::endl;
return os;
}
This defines an "output operator" for your custom type, so that the compiler knows what to do when you ask it to do something like: cout << nacion1;
Also, you want to get rid of >> endl in cin >> eligNac >> endl;, and you probably want to do comparison if(eligNac == 1) instead of assignment if(eligNac = 1).

c++ function redefining (code not working - logic error)

I am currently learning c++ and i am now working on Inheritance.
I have to make a regular question class as well as a derived class that is a Numeric question and a multiple choice question. I make the questions in the code, and then display them 1 by 1 to the user. The user then answers the questions, and the program is supposed to check whether the answer is correct.
#include <iostream>
#include <string>
using namespace std;
class Question {
protected:
string text;
string answer;
string input;
public:
Question(string inText, string inAnswer) {
text = inText;
answer = inAnswer;
}
Question() {
text = "blank question";
answer = " ";
}
void setQuestion(string txt) {
text = txt;
}
void setAnswer(string answr){
answer = answr;
}
void userAnswer(string ans) {
input = ans;
}
string getAnswer() {
return answer;
}
string getQuestion() {
return text;
}
void displayQuestion() {
cout << getQuestion() << endl;
}
void isCorrect() {
cout << "default function" << endl;
if (input.compare(answer) == 0)
cout << "True" << endl;
else
cout << "False" << endl;
}
};
class NumericQuestion : public Question {
protected:
double ans;
double inp;
public:
NumericQuestion(string inText, double inAns) {
text = inText;
ans = inAns;
}
void userAnswer(string ans) {
inp = stod(ans);
}
void isCorrect() {
cout << "numeric function" << endl;
if (inp == ans)
cout << "True" << endl;
else if ((inp - ans) <= 0.01)
cout << "False" << endl;
else
cout << "False" << endl;
}
};
class MultipleChoice : public Question {
protected:
string qA, qB, qC, qD;
public:
MultipleChoice(string inText, string qA, string aB, string qC, string qD, char inAnswer) {
text = inText;
answer = inAnswer;
}
void displayQuestion() {
cout << text << endl;
cout << "a) " << qA << " " << "b) " << qB << endl;
cout << "c) " << qC << " " << "d) " << qD << endl;
}
};
int main() {
string ans;
Question q1("whats 2+2", "four");
NumericQuestion q2("2+2", 4);
MultipleChoice q3("The Right Answer is C", "answer A", "thisisB", "thats C", "Wrong", 'c');
Question arr[] = { q1,q2,q3};
for (int i = 0; i < 3; i++) {
arr[i].displayQuestion();
cin >> ans;
arr[i].userAnswer(ans);
arr[i].isCorrect();
}
getchar();
return 0;
}
The member function isCorrect() from NumericQuestion class and displayQuestion() from MultipleChoice class don't get used, instead, the ones from Question class get used, which lead to logical errors in my code.
You're slicing objects when you assign subclasses of Questions by value to an array of Question when you do Question arr[] = { q1, q2, q3 };. This means that even though some of your derived Question objects have extra members that the base class doesn't, they're being truncated away by the assignment into the array. Another problem is that because arr is declared to hold plain and simple Question objects, the compiler will assume that a call like arr[i].isCorrect(); will always refer to Question::isCorrect(), and not a derived method. Here's a couple things to fix.
Make overridable functions virtual:
class Question {
...
virtual void isCorrect() {
cout << "default function" << endl;
if (input.compare(answer) == 0)
cout << "True" << endl;
else
cout << "False" << endl;
}
and override them in subclasses:
class NumericQuestion : public Question {
...
void isCorrect() override {
cout << "numeric function" << endl;
if (inp == ans)
cout << "True" << endl;
else if ((inp - ans) <= 0.01)
cout << "False" << endl;
else
cout << "False" << endl;
}
Finally, avoid the slicing by storing base class pointers to your Questions. Here, I'm using std::shared_ptr to avoid the headaches of manual memory management. Also appearing is a ranged-for loop:
auto q1 = std::make_shared<Question>("whats 2+2", "four");
auto q2 = std::make_shared<NumericQuestion> q2("2+2", 4);
auto q3 = std::make_shared<MultipleChoice>("The Right Answer is C", "answer A", "thisisB", "thats C", "Wrong", 'c');
// even though q1...q3 are shared_ptrs to derived classes, they can be safely cast to shared_ptrs to the base class
std::vector<std::shared_ptr<Question>> questions { q1, q2, q3 };
for (const auto& question: questions) {
question->displayQuestion();
cin >> ans;
question->userAnswer(ans);
question->isCorrect();
}
You need to set userAnswer, displayQuestion and isCorrect as virtual in the base class.
You also need to store your question as pointers (there's other options) to prevent slicing. Personally, I find it simpler to fix it like this:
Question* arr[] = {&q1,&q2,&q3};
...
arr[i]->displayQuestion();
(you need to change all usage or arr[i] to use arrows)
There are two issues at play here.
1) Based on your for loop at the end, you need to declare some functions, like displayQuestion(), userAnswer(), and isCorrect() as virtual.
2) Secondly, change your arr declaration to Question *arr[] = {&q1, &q2, &q3};.

C++ error: expected primary-expression before '(' token [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So I know my code is a mess. I have an overdue homework assignment for operator overloading and I have been failing miserably and trying to make it work.
The gist of it is: Define a unary number class Unary to the following specifications.
The class should represent numbers using all 1's, so, for example, 11111 represents 5 and 1111111111 represents 10 and the empty string represents 0. We have to do << >> + - ++ & --(post and pre).
Ok. So far I have only been able to get the << >> and + operator to work. So I am working on the - right now and I get this error:
100:17: error: expected primary-expression before '(' token
100:26: error: expected primary-expression before ')' token
I am using g++.
Here is my code. I've marked line 100 with a //######################################
#include <iostream>
#include <cstdlib>
#include <sstream>
using namespace std;
class Unary {
friend ostream& operator<<(ostream& outputStream, const Unary& output);
friend istream& operator>>(istream& inputStream, Unary& input);
public:
Unary();
~Unary();
Unary(int&);
string toString();
Unary operator+(const Unary&);
Unary operator-();
Unary& operator++();
const Unary operator++(int);
// Unary& operator--();
private:
int x, myInt;
string myString;
};
int main() {
// variable for manipulating
Unary uNum;
Unary uNum2;
Unary uNumAns;
Unary uNumAns2;
cout << "Please enter a number by representing it with 1's: ";
cin >> uNum;
cout << "uNum has " << uNum << ". " << endl;
cout << "Please enter a number by representing it with 1's: ";
cin >> uNum2;
cout << "uNum2 has " << uNum2 << ". " << endl;
uNumAns = uNum + uNum2;
cout << "uNum (" << uNum << ") + uNum2 (" << uNum2 << ") = uNumAns ("
<< uNumAns << ") " << endl;
cout << "uNumAns is " << uNumAns << endl;
cout << "** After ++uNumAns, uNumAns is " << uNumAns << endl;
// cout << "uNumAns2 is " << uNumAns2 << endl;
// --uNumAns2;
// cout << "** After --uNumAns, uNumAns2 is " << uNumAns2 << endl;
// cout << "\nuNumAns before uNumAns++ is " << uNumAns;
// uNumAns++;
// cout << "uNumAns after uNumAns++ is " << uNumAns << endl;
return 0;
}
// default constructor
Unary::Unary() : myInt(0) {}
Unary::Unary(int& newInt) : myInt(newInt) {
myString = this->toString();
cout << " in Unary(int) : myInt is " << myInt << "& myString is "
<< myString << endl;
}
// deconstructor
Unary::~Unary() {}
ostream& operator<<(ostream& outputStream, const Unary& output) {
outputStream << output.myString;
return outputStream;
}
istream& operator>>(istream& inputStream, Unary& input) {
string str;
inputStream >> str;
input.myString = str;
return inputStream;
}
Unary& Unary::operator++() {
this->myString += 1;
return *this;
}
// Unary& Unary::operator--() {
// this->myString = myString - 1;
// return *this;
// }
const Unary Unary::operator++(int post) {
myInt = myString.length();
Unary* answer = new Unary(myInt);
myInt += 1;
return *answer;
}
Unary Unary::operator-() {
// int newx = lhs.x - rhs.x;
// Unary *answer = new Unary(newx);
myInt = myString.length();
return Unary(-myInt&); //######################################## THIS IS LINE 100
}
Unary Unary::operator+(const Unary& rhs) {
// myInt = this->myInt + rhs.toString();
Unary* answer = new Unary;
answer->myString = myString + rhs.myString;
return *answer;
}
string Unary::toString() {
string str = "";
myInt = myString.length();
cout << "\n (changing an int to a string) You entered " << myInt;
for (int i = 0; i < myInt; i++) {
str += "1";
}
myString = str;
cout << " ** myString is " << myString << " ** " << endl;
return str;
}
I think you meant for this:
return Unary(-myInt&);
to be:
return Unary(-myInt);
The ampersand is a syntax error there.

final project, Dynamic Programming. Need second set of eyes

I feel really stupid coming to ask this question here today after bugging everyone yesteday on understanding the algorithm. But I am not looking at this thing straight anymore. Anyways, it is a knapsack probled, solved with memoization and dynamic progrmming. The problem is that the printout of my answers is not matching the requierements.
All I want is a second look at it and if someone can point me where I am wrong at.
Appreciated for all the help.
This is the ProfitHeader.h file
#ifndef PROFITHEADER_H_
#define PROFITHEADER_H_
#include <string>
#include <map>
#include <vector>
using namespace std;
namespace kproblem{
typedef int Money;
typedef int Labor;
struct Resources{
Money liquidity;
Labor officeWork;
Labor programmingWork;
Resources(Money li, Labor of, Labor pro) : liquidity(li), officeWork(of), programmingWork(pro){}
//operator -=
Resources & operator -=( const Resources &rhs ){
liquidity -=rhs.liquidity;
officeWork -=rhs.officeWork;
programmingWork -=rhs.programmingWork;
return *this;
}
//operator< Used to make sure that key elements Match. will not modify (this)
bool operator<(const Resources & rhs) const{
if(this->liquidity < rhs.liquidity)
return true;
else if(this->liquidity > rhs.liquidity)
return false;
else if(this->officeWork < rhs.officeWork)
return true;
else if(this->officeWork > rhs.officeWork)
return false;
//this is the iff conditional
else if(this->programmingWork < rhs.programmingWork)
return true;
else
return false;
}
};
//Global Operator-. This will not modify (this).
Resources operator-( const Resources & lhs, const Resources & rhs ){
return Resources(lhs.liquidity - rhs.liquidity,
lhs.officeWork - rhs.officeWork, lhs.programmingWork - rhs.programmingWork);
}
//This is the Project Struct. It should contain the resources and data from the file.
struct Project{
string name;
Resources resources;
Money profit;
Project(string n, Resources re, Money p) : name(n), resources(re), profit(p) {}
};
//Definition of the ValueMap
typedef map<pair<Resources, vector<Project>::size_type>, pair<Money, bool>> ValueMap;
}
#endif
This is my main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <exception>
#include "ProfitHeader.h"
using namespace std;
using namespace kproblem;
//The following was provided to us on the program
class IO_Exception : public runtime_error
{
public:
IO_Exception(const string & message) : runtime_error(message) { }
};
void readProjects(vector<Project> & projects, const string & fileName)
{
ifstream infile(fileName.c_str());
if (!infile)
throw IO_Exception("Could not open " + fileName);
string oneLine;
unsigned int lineNum = 0;
while (getline(infile, oneLine))
{
istringstream st(oneLine);
lineNum++;
string name;
Money liquidity;
Labor officeWork;
Labor programmingWork;
Money profit;
st >> name;
st >> liquidity;
st >> officeWork;
st >> programmingWork;
st >> profit;
if (st.fail())
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
string junk;
if (st >> junk)
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
projects.push_back(Project(name, Resources(liquidity, officeWork, programmingWork), profit));
}
if (!infile.eof())
throw IO_Exception("Error reading from " + fileName);
}
//Class Best Profit.
//This class will calculate the best possible profit we can get.
Money bestProfit(const vector<Project> & projects, Resources res, ValueMap & valMap,int n){
//initialize the best 2 possible solutions.
Money best1;
Money best2;
Money map; // the map where ou answers are stored
// First check if we are not at the end of the projects
if(n == 0){
return 0;
}
//now we are going to check the best project possible.
//Check the subinstance if it was solved.
if(valMap.find(make_pair(res, n-1)) != valMap.end()){
map = valMap.find(make_pair(res, n-1))->second.first;
return map;
}//check if the subinstance is solved. if it is return the value.
best1 = bestProfit(projects, res, valMap, n-1);//first best possible solution
//check the resources for the last project only. Fopr the second best possible solution.
if(res.liquidity >= projects.at(n-1).resources.liquidity
&& res.officeWork >= projects.at(n-1).resources.officeWork
&& res.programmingWork >= projects.at(n-1).resources.programmingWork){// feasability Check.
//all the above are requiered as it is necessary to check for all of them when doing the calculations.
best2 = bestProfit(projects, res - projects[n-1].resources, valMap, n-1) + projects[n-1].profit;
}
else{
best2 = 0;
}
//after the whole check compare the results and store the best possible result in the map.
if(best1 >= best2){
valMap.insert(make_pair(make_pair(res, n), make_pair(best1,false)));
return best1;
}
else{
valMap.insert(make_pair(make_pair(res, n), make_pair(best2,true)));
return best2;
}
}
//reportBestProfit. This will call Best profit and help us print the final results.
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
for(int i= 1; i <= 1000; i++){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//if(valueMap.find(make_pair(resources, i))->second.first != valueMap.find(make_pair(resources, i-1))->second.first){
//cout << valueMap.find(make_pair(resources, i))->second.first; //money
//cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " " << projects.at(i-1).name << " " << projects.at(i-1).resources.liquidity <<" ";//projects
cout << projects.at(i-1).resources.officeWork << " " << projects.at(i-1).resources.programmingWork;
cout << " " << projects.at(i-1).profit << endl;//profit
//}
}
}
cout << "Total Resources Used -" << endl;
//Print the resources consumed.
for(int i= 1; i <= 1000; i++){
if(valueMap.find(make_pair(resources, i))->second.second == true){
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
int main()
{
vector<Project> projects;
try
{
readProjects(projects, "Proj5Data.txt");
}
catch (const IO_Exception & ex)
{
cerr << "IO error from: " << ex.what() << endl;
return 1;
}
//these values can be changed for different analysis on projects.
Money liquidity = 200;
Labor officeWork = 450;
Labor programmingWork = 1000;
cout << "Available resources - " << endl
<< " Liquidity: " << liquidity << endl
<< " Office Work: " << officeWork << endl
<< " Programming Work: " << programmingWork << endl;
reportBestProfit(projects, Resources(liquidity, officeWork, programmingWork));
return 0;
}
The project file that contains the projects can be downloaded temporarily here:
https://rapidshare.com/files/459861869/Proj5Data.txt
my guess is the problem is on the valmap find, but I have tried all kinds of combinations and it does not work at all.
Finally this is the final printout I should be getting from this:
But instead I am getting all these other results, including some of the ones I need:
Again thank you for the one that can slap me in the head and say, you FOO, you shouldn't be doing this anymore :).
removing this would get rid of the leading numbers on the second part of the output
cout << valueMap.find(make_pair(resources, i))->second.first; //money
cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " "
the values you print at this point haven't been filtered by and ordered by which is why i think your printing these values
but you don't have code to print "The total resources used -" part
OK, so yes I do have an answer. Is now complete (after edit)
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
vector<Project> result;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
// this loop just iterates through the values, it does not check the initial resources.
for(int i= 999; i > 0; i--){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
//check first If I still have resources available
if(resources.liquidity >=0 && resources.officeWork >= 0 && resources.programmingWork >= 0){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//when I find the first true, I need to substract the resources of it from the base resources,
//to ask the question again.
resources.liquidity -= projects.at(i-1).resources.liquidity;
resources.officeWork -= projects.at(i-1).resources.officeWork;
resources.programmingWork -= projects.at(i-1).resources.programmingWork;
//Push the results into a vector for the printout
result.push_back(Project(projects.at(i-1).name,
Resources(projects.at(i-1).resources.liquidity,
projects.at(i-1).resources.officeWork,
projects.at(i-1).resources.programmingWork),
projects.at(i-1).profit));
//Also in one shot add together the resources used
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
}
//Print the saved vector in reverse order
for(int size = result.size(); size != 0; size--){
cout << " " << result.at(size -1).name;
cout << " " << result.at(size -1).resources.liquidity;
cout << " " << result.at(size -1).resources.officeWork;
cout << " " << result.at(size -1).resources.programmingWork;
cout << " " << result.at(size -1).profit << endl;
}
cout << "Total Resources Used -" << endl;
////Print the resources consumed.
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
Basically I was not substracting the resources, so I was always having over resources, but once I did that viola! it works. Thank you guys for looking at it, I guess I just needed inspiration this morning.

How do I search a book list class by the author's last name but with multiple authors?

So I finished my project, but my only problem is that I can only search one author at a time. I seem to not be able to figure it out.
This is what I have..am I missing something thats not making me able to find more than one author's last name?
void BookRecordUI::FindBookLast() //allows us to search a book by the last name of the author from the book record...
{
string Last;
cout << "Enter Book by Last Name of Author: " << endl;
getline(cin, Last);
Collection.FindBookAuthorLast(Last);
}
Any help will be much appreciated!
EDIT: So basically I want to find multiple authors..for example, if I inputted John Hopkins and Wilson Greene, I want to pull both authors last name at the same time. Sorry for not clearly explaining it.
I also have this part as well..
void BookRecordList::FindBookAuthorLast(string Last)
{
int K;
for(K = 0; K < (int)List.size(); K++)
if(List[K].GetAuthorLast() == Last)
cout << List[K].GetTitle() << " " << List[K].GetAuthorFirst() << " " << List[K].GetAuthorLast() << " " << List[K].GetPublisher() << " " << List[K].GetPublisherAddress() << " " << List[K].GetPublisherPhone() << " "
<< List[K].GetPublisherContact() << " "<< List[K].GetCategory() << " " << List[K].GetDate() << endl;
};
My whole program is really long, so I dont want to overwhelm you guys by posting the whole thing up..
You may need to change your Book definition to enable searching for multiple authors:
struct Author
{
std::string& get_name() const;
};
struct Book
{
std::vector<Author> m_authors; // A book can have 1 or more authors
bool has_author(std::string author_name) const
{
std::vector<Author>::const_iterator iter;
for (iter = m_authors.begin();
iter != m_authors.end();
++iter)
{
if (iter.get_name() == author_name)
{
return true;
}
}
return false;
};
The objective now is to write a predicate or functor that will call Book::has_author.
This is one solution to your issue, there are probably others when you give it more thought.
You do not give us a lot of informations about what is a "book" and what is a Collection.
But, it seems that you already implement a function that returns you the expected result for one string (the last name of an author).
What you can do is use multiples times your function FindBookAuthorLast with a different last name each time.
Or, implement a function that takes a vector of string in parameters and that returns you a vector of Book (or whatever is your class containing the books).
EDIT :
With the new informations you posted, here is a way to do it :
(This is not the only solution to do it, there is a lot)
(Code not compiled, not tested)
void BookRecordList::FindBookAuthorLast(vector<string> Last)
{
int K;
vector<string>::iterator author_it = Last.begin();
for ( ; author_it != Last.end(); ++author_it)
{
for(K = 0; K < (int)List.size(); K++)
if(List[K].GetAuthorLast() == *author_it)
cout << List[K].GetTitle() << " " << List[K].GetAuthorFirst() << " " << List[K].GetAuthorLast() << " " << List[K].GetPublisher() << " " << List[K].GetPublisherAddress() << " " << List[K].GetPublisherPhone() << " "
<< List[K].GetPublisherContact() << " "<< List[K].GetCategory() << " " << List[K].GetDate() << endl;
}
};
To build the vector<string> to give to the function FindBookAuthorLast, iterate on getline().
Maybe all you want is to loop over your function:
void BookRecordUI::FindBookLast() //allows us to search a book by the last name of the author from the book record...
{
string Last;
do {
cout << "Enter Book by Last Name of Author: " << endl;
getline(cin, Last);
Collection.FindBookAuthorLast(Last);
}
while(!Last.empty());
}
(not tested).