Accessing private members within a class? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Why do we have to copy first then use the getfunction? Why can we just directly use the get function on like borrowers.getID() == ID instead of borrow.getID() == ID?
I just need an explanation. I know some things might be missing but I am just very confused here as it looks not very efficient!
class ReadershipList {
private:
ifstream myin;
ofstream myout;
string readerfile;
vector<Borrower> borrowers;
public:
int findBorrowerbyID(string ID); //Find the borrowers index by ID
int findBorrowerbyName(string name);
void addBorrower(Borrower newBorrow); //Add a borrower to the vector of borrowers
void listBorrowers(); //Prints the list of borrowers
bool deleteBorrower(string ID); //Delete borrower using ID
Borrower getBorrowerbyID(string ID); /
Borrower getBorrowerbyName(string name); //Get borrower details using name
};
Why cant I directly access the members?
Instead of using this:
bool ReadershipList::deleteBorrower(string ID) {
Borrower borrow;
for (int b = 0; b < borrowers.size(); b++) {
borrow = borrowers[b];
if (borrow.getID() == ID) {
borrowers.erase(borrowers.begin() + b);
return true;
}
}
return false;
}

you do not need to copy, you can do
bool ReadershipList::deleteBorrower(string ID) {
for (int b = 0; b < borrowers.size(); b++) {
if (borrowers[b].getID() == ID) {
borrowers.erase(borrowers.begin() + b);
return true;
}
}
return false;
}
or
bool ReadershipList::deleteBorrower(string ID) {
for (int b = 0; b < borrowers.size(); b++) {
Borrower & borrow = borrowers[b]; // or better "const Borrower & borrow = borrowers[b];" if "string Borrower::getID() const"
if (borrow.getID() == ID) {
borrowers.erase(borrowers.begin() + b);
return true;
}
}
return false;
}

Related

Sorting function in a class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a class Client :
#include <stdio.h>
#include <iostream>
class Client
{
private:
vector<Liked*>like;
public:
Client();
~Client();
sort_id();
};
where like is a vector connection between class Client and Liked.
I created adding function:
void Client::addLiked(int id, string title)
{
Liked* newLiked= new Liked(id, title, year, minute, genre);
like.push_back(newLiked);
return ;
}
which is responsible for adding movie to the list. I would like to have sorting function, which will sort id in ascending order while printing the whole list :
void Client::print_Liked()
{
int n = like.size();
if(n == 0)
{
cout<<"Is empty"<<endl;
}
for(int i=0;i<n;i++)
{
sort_id();
like[i]->print_Liked();
}
}
I have tried with a bubble sort but I got errors :
void Client::sort_id()
{
int n = like.size();
bool swapped = true;
int j = 0;
int temp;
while (swapped) {
swapped = false;
j++;
for(int i = 0;i < n - j;++i)
{
if(like[i]->getID() > like[i+1]->getID())
{
temp = like[i]->getID();
like[i]->getID() = like[i+1]->getID();
array[i+1]->getID() = temp;
swapped = true;
}
}
}
}
The easiest way to sort your vector is by using the standard std::sort function together with a suitable lambda function for the comparisons.
Something like this:
void Client::sort_id()
{
std::sort(begin(like), end(like), [](Liked const* a, Liked const* b)
{
return a->getID() > b->getID();
});
}

Why is my code for prefix to infix not displaying an output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am writing this code on Visual studio 2019 which converts a prefix number to infix.
When i press F5 the window says: (process 10428) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
I don't know much about C++. I know Java and python fairly well but our instructor wants us to use C++.
string s[7];
int f = -1;
void push(string a)
{
s[f++] = a;
}
string pop()
{
return s[f--];
}
bool isop(char x) {
switch (x)
{
case '+':
case '-':
case '*':
case '/':
return true;
}
return false;
}
int main() {
string a = "*+ab+cd";
reverse(a.begin(), a.end());
for (int i = 0;i<int(a.length());i++) {
if (isop(a[i])) {
string v1 = pop();
string v2 = pop();
string h = "(" + v1 + a[i] + v2 + ")";
push(h);
}
else {
push(string(1, a[i]));
}
}
for (int i = 0;i < 7;i++)
{
cout << s[i];
}
return 0;
}
Problem here (it would be exactly the same in Java)
string s[7];
int f = -1;
void push(string a)
{
s[f++] = a;
}
The first time you push f is -1 so you have an out of bounds array access. I guess you meant this
void push(string a)
{
s[++f] = a;
}
You could have avoided this error by using a std::vector (similar to an ArrayList in Java).

Errors with Unsorted List? [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 have a homework assignment due tonight and I'm trying to compile it to test but I'm running into a bunch of errors and some of them seem to make zero sense? The errors mention things like: "syntax error before '::'" and the like, but I have never encountered errors like these and have 0 idea on how to fix them.
UnsortedClass.cpp
#include "UnsortedClass.h"
void UnsortedType::UnsortedType()
{
length = 0;
}
bool UnsortedType::IsFull() const
{
return (length == MAX_ITEMS);
}
int UnsortedType::GetLength() const
{
return length;
}
NBA UnsortedType::GetItem(NBA customPlayer, bool& found)
{
bool moreToSearch;
int location = 0;
found = false;
moreToSearch = (location < length);
while (moreToSearch && !found)
{
switch (customPlayer.ComparedTo(info[location]))
{
case LESS :
case GREATER : location++;
moreToSearch = (location < length);
break;
case EQUAL : found = true;
item = info[location];
break;
}
}
return customPlayer;
}
void UnsortedType::MakeEmpty()
{
length = 0;
}
void UnsortedType::PutItem(NBA customPlayer)
{
info[length] = customPlayer;
length++;
}
void UnsortedType::DeleteItem(NBA customPlayer)
{
int location = 0;
while (customPlayer.ComparedTo(info[location]) != EQUAL)
location++;
info[location] = info[length - 1];
length--;
}
void UnsortedType::ResetList()
{
currentPos = -1;
}
NBA UnsortedType::GetNextItem()
{
currentPos++;
return info[currentPos];
}
UnsortedClass.h
#include "NBA.h"
class UnsortedClass //declares a class data type
{
public:
// 8 public member functions
void UnsortedType ( );
bool IsFull () const; //checks if list is full
int GetLength () const ; // returns length of list
NBA GetItem (NBA customPlayer, bool& found); //gets item specified in parameters
void PutItem (NBA customPlayer); //puts NBA player in list
void DeleteItem (NBA customPlayer); //deletes NBA player from list
void ResetList (); //resets list to 0
NBA GetNextItem (); //gets next item after current list position
private:
// 3 private data members
int length;
NBA info[MAX_ITEMS];
int currentPos;
};
NBA.h
#include <string>
using namespace std;
const int MAX_ITEMS = 10;
enum RelationType {LESS, GREATER, EQUAL};
class NBA {
private:
char firstInitial;
string lastName;
string team;
char position;
public:
void set_first_initial(char playerFirstInitial);
void set_last_name(string playerLastName);
void set_team(string teamName);
void set_position(char position);
char get_first_initial();
string get_last_name();
string get_team();
char get_position();
};
The errors I've been receiving are as follows (in picture format as I can't paste the lines without Stackoverflow interpreting it as code)
Constructors don't have a return type specified. Change
void UnsortedType::UnsortedType()
to
UnsortedType::UnsortedType()
Also the class name in its header declaration is wrong; everywhere else says UnsortedType but this says:
class UnsortedClass //declares a class data type

Sorting list. What is wrong with my sorting method? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a real headache with my sorting method. I don't know what can be wrong? I have checked sorting method millions of times and I still messed up with it.
Here are my code
struct Man{
string name;
string adress;
bool operator < (const Man & next);
};
bool Man::operator < (const Man & next){
return adress < next.adress && name < next.name;
}
struct SarV{
Man duom;
SarV *sekV;
};
struct SarH{
string date;
SarH *sekH;
SarV *prV;
};
void Branch::Check(string code, int month){
ofstream rf("Rezultatai.txt", ios::app);
rf.setf(ios::left);
SarH *d = pr;
rf << "Data" << endl;
while(d != NULL){
SarV *v = d->prV;
Print(rf, v, code, month);
d = d->sekH;
}
rf.close();
}
Here are my sorting function
void Branch::Sort(){
string temp;
for(SarH *s = pr; s != NULL; s = s->sekH){
for(SarV *p = s->prV; p != NULL; p = p->sekV){
for(SarV *p2 = p; p2 != NULL; p2 = p2->sekV){
if(p2->duom < p->duom){
//---------------------------------------
temp = p->duom.name;
p->duom.name = p2->duom.name;
p2->duom.name = temp;
//---------------------------------------
temp = p->duom.adress;
p->duom.adress = p2->duom.adress;
p2->duom.adress = temp;
//---------------------------------------
}
}
}
}
}
So what's wrong with it?
Your operator is likely wrong.
Try this:
bool Man::operator < (const Man & next){
if(adress < next.adress) return true;
if(adress == next.adress) {
if(name < next.name) return true;
}
return false;
}

Base changing algorithm in c++/c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the following function:
template <class T>
T c_base (T num,T second, T first = 10)
{
T res = 0;
T secnum;
T bitseed[90];
int i = 1,k,jump,anex,len;
if(second==first)
{
res = num;
return (res);
}
if(first==10&&second!=10)
{
anex = num;
while(num>0)
{
jump = num/second;
bitseed[i] = num%second;
num/=second;
i++;
}
if(anex>0)
{
for(k=i;k>=1;k--)
{
if(k==i&&jump==0) {res = bitseed[k-1]; k--; continue;}
if(k==i&&jump!=0) {res = jump; continue;}
res = res*10+bitseed[k];
}
}
return (res);
}
if(second==10)
{
anex = num;
len = 1;
while(anex>=10)
{
len *= 10;
anex/=10;
i++;
}
anex = num;
if(anex>0)
{
for(k=i;k>=1;k--)
{
res = res*first+anex/len;
anex%=len;
len/=10;
}
}
return (res);
}
if(second!=10&&first!=10)
{
secnum = c_base <T> (num,10,first);
res = c_base <T> (secnum,second,10);
return (res);
}
}
I was wondering how efficient it is (from both speed and memory consumed point of view) and how/if can it be improved. (from the algorithm perspective)
Ps. Explication of function : c_base("number","to-base","from-base"->optional);
I see a lot of confusion here:
A number doesn't have a base. What do have bases are number representations. Both input and output should be number representations (e.g. std::strings in C++).
Why treating base 10 specially? there's nothing really special about it except that by historical accidents most humans today use it. This is totally irrelevant for an algorithm. A special case for power-of-two bases could make sense for technical reasons (because computers use base 2 internally).
Why doing a double conversion instead of just reading from base x and writing to base y?