c++ oop homework help ??

I have c++ homework due tomorrow and need help.. i tried learning online but no help.. if anyone can help , please do . basically i have to write the class and functions for the main function.. and idk where to start. i paid attention but still very confusing.

1. Complete the program. Sort the cards in order least to greatest

int main() {
vector<Card> cards(5);
cards[0].setNumber (2);
cards[1].setNumber(6);
cards[2].setNumber(10);
cards[3].setNumber(7);
cards[4].setNumber(5);

sort_cards(cards);
print_cards(cards);
return 0;
}
Last edited on
I have no idea why I'm still awake.

But alas, I am.

Do you have a class declaration given to you?
Giving you this program and saying "complete it" is very vague.

What have you tried so far?
no i don't have a class declaration.. my professor just told me to write the header files and class for the main program.. and I'm confused as how to start it
That's unusual, but alright.

Well, from what I can see, it looks like there is only one class used here - "cards".
What sort of member variables does it look like it has? What sort of functions does it look like it has? are "sort_cards" and "print_cards" member functions or just functions that take a "cards" object?
sort and print are just regular functions using sort from <algorithm> library
here is what i did so far:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


void sort_cards( vector<int> cards){

sort(cards.begin(), cards.begin() + 4);

}

class Card{
public:
vector<int> cards;

void setNumber (int x) {
cards.push_back(x);
}

};

int main() {
vector<Card> cards(5);
cards[0].setNumber (2);
cards[1].setNumber(6);
cards[2].setNumber(10);
cards[3].setNumber(7);
cards[4].setNumber(5);

sort_cards(cards);
print_cards(cards);
return 0;
}
Alright. The sort looks OK, except for one thing:

sort(cards.begin(), cards.begin() + 4);
You might want to change that '4' to cards.size();. There are actually 5 cards, not 4.

Do you have sample output for the "print_cards" function? What is the output supposed to looks like?
the output is just the numbers in order .. like 2,5,6,7,10
also I'm confused as to whether the class name should be called Card or cards
vector<Card>. You put the type name in <>.
my professor wrote that code .. maybe it's a typedef? like for every int , the alias would be Card ? or am I wrong
A vector can store anything - it uses templates.

If you want to have a vector of integers, you can use vector<int>.
If you want a vector of strings, you can use vector<string>

There's a bit about templates that I'd have to talk about to really explain it, but a vector can hold any class/item (as long as it is instantiable). But you have to tell it what it is holding by putting the type (class name) inside the '<>'.
Topic archived. No new replies allowed.