how to print to screen a vector? - class

I'm implementing the show Deal Or No Deal, there's a class 'box' which in the main file i used to store the random values of the boxes and than, i saved each box in the vector. im trying now to print in the screen the boxes saved in the vector whit the iterator,without succeeding, any help???
//random assignation of pound value to the 22 boxes
for (int e = 1; e < 23; e++)
{
int pos;
bool op = true;
while (op)
{
pos = rand();
if (pos > 0 && pos < 23)
{
if (myArray[pos][1] == 0)
{
myArray[pos][1] = 1;
op = false;
}
}
}
box b(e, myArray[pos][0]); //creating the class box
game_box.push_back(b); //function of the vector to insert a data in it
}
//show boxes
for (auto a = game_box.begin(); a!= game_box.end(); a++)
{
cout << *a << endl;
}

You first need to remove the dereference operator (*) from the a.
Next you need to add an output operator for box. Assuming that box is a class with member data member1 and member2 this would look something like:
friend std::ostream& operator<< (std::ostream &out, const box& b)
{
out << box.memeber1 << " " << box.member2;
}
The key point is that you need to define this operator for every class.
Once you've done that and got it working you might also like to look at this library which defines << operators for all stl containers. This lets you replace
for (auto a = game_box.begin(); a!= game_box.end(); a++)
{
cout << *a << endl;
}
by simply
cout << game_box << endl;

this works..
class Box
{
float pound_contained;
int box_number;
public:
Box(int box_number, float pound_contained);
int getbox_number();
float getpound_contained();
};
int Box::getbox_number()
{
return this->box_number;
}
float Box::getpound_contained()
{
return this->pound_contained;
}
main()
{
vector<Box> game_box;
Box* boxes = &game_box[i];
cout <<boxes->getbox_number()<<endl;
}

Related

how to point at multiply struct with one struct pointer in c++

Write a assign_obj.h file so that the assign_driver file will output the
following. When implementing assign_obj.h think about how efficient your program will run. You must
implement your assign_obj class using a dynamic array.
assign_obj:: assign_obj() function will just set size to zero
assign_obj:: assign_obj(std::string s) function will go through each character of string and convert it to uppercase and push it the last of A
std::ostream& operator<<(std::ostream & out, assign_obj & obj) function will go through each data in obj.A vector and convert integer into string and
than output the data in this format [value:count value:count ....]
class assign_obj{
private:
struct item{
char value;
int count;
};
item *A;
int size;
public:
assign_obj();
assign_obj(std::string);
friend std::ostream& operator<<(std::ostream & out, assign_obj & obj);
}
int main(){
assign_obj ao1("dsdfdf");
std::cout << ao1 << std::endl;
}
This is the output that I want
[ D:1 S:1 D:1 F:1 D:1 F:1 ]
assign_obj:: assign_obj(){
size = 0;
}
assign_obj:: assign_obj(std::string s){
size = s.size();
for(int i = 0; i < s.size(); i++){
char c = std::toupper(s[i]);
A = new item{c,1};
}
}
# std::ostream& operator<<(std::ostream & out, assign_obj & obj){
std::cout<< "size: " << obj.size <<std::endl;
out << "[ ";
for(int i = 0; i < obj.size; i++){
out << obj.A[i].value << ":" << std::to_string(obj.A[i].count) << " ";
}
out << "]" << "\n";
return out;
}

Finding the smallest and largest numbers by single linked list and two classes

I got several numbers from user by single linked list and my program's task is finding the smallest and largest number in the linked list by two classes and print them on the sreen. But after a time, my program got closed and i didn't see anything. What went wrong?
#include<iostream>
using namespace std;
struct Node
{
double Number;
struct Node *Point;
} *End = nullptr;
typedef struct Node node;
namespace Min_Max
{
class Min
{
node *Result = End;
public: Min()
{
if(Result == nullptr)
{
cout << "You didn\'t enter anything!\a";
system("pause");
exit(EXIT_FAILURE);
}
node *Counter = Result->Point;
while(Counter != nullptr)
{
if(Counter->Number < Result->Number)
Result = Counter;
Result = Result->Point;
}
}
node* Show()
{
return Result;
}
};
class Max
{
private:
node *Result = End;
public:
Max()
{
if(Result == nullptr)
{
cout << "You didn\'t enter anything!\a";
system("pause");
exit(EXIT_FAILURE);
}
node *Counter = Result->Point;
while(Counter != nullptr)
{
if(Counter->Number > Result->Number)
Result = Counter;
Result = Result->Point;
}
}
node* Show()
{
return Result;
}
};
};
int main()
{
node *linker = nullptr;
register short int Counter = 1;
while(1)
{
linker = new node;
if(linker == nullptr)
{
cout << "An error occurred during allocating memory." << endl << endl;
system("pause");
return 0;
}
cout << "Number " << Counter << ": Enter your number: ";
cin >> linker->Number;
system("cls");
if(linker->Number == 0)
{
delete linker;
break;
}
linker->Point = End;
End = linker;
Counter++;
}
Min_Max::Min Min;
Min_Max::Max Max;
cout << "The smallest number is " << (Min.Show())->Number << endl;
cout << "The largest number is " << (Max.Show())->Number << endl;
return 0;
}
My C++ compiler is GCC-C++11 and my operating system is Windows 10.

C++ Cant Change Object's Variables

class ship {
public:
int location;
int length;
};
void createship(ship ship1, int gridsize) { //function to set ship1's length and location
srand(time(NULL));
ship1.length = (int)((rand()) % gridsize) / 4 + 1;
ship1.location = (int)(rand()) % gridsize;
}
void insertship(ship ship1, vector <char> grid) { //insert ship into grid, change grid's elements from 'e' to 'f'
for (int temp2= 0; temp2 < ship1.length; temp2++) {
grid[ship1.location + temp2] = 'f';
}
}
int main()
{
int gridsize;
cout << "Gridsize: ";
cin >> gridsize;
cout << "\n";
vector <char> grid(gridsize, 'e');
for (int temp3 = 0; temp3 < grid.size(); temp3++) { //cout vector grid
cout << grid[temp3];
}
cout << "\n";
ship* ship1 = new ship(); //create ship1
createship(*ship1, gridsize);
insertship(*ship1, grid);
cout << (*ship1).length << "\n";
cout << (*ship1).location << "\n";
for (int temp4 = 0; temp4 < grid.size(); temp4++) { //cout vector grid again (with ship)
cout << grid[temp4];
}
return 0;
}
My ship1.length and ship1.location always remain as zero, even though the createship() function is supposed to change it to a random figure? Is there any mistake I made?
Just to add more words below because stackexchange doesn't allow me to add mostly code in my question
You were passing a parameter by value which will create and change a local variable in the function instead of the source variable.
You should pass the parameter by reference.
void createship(ship &ship1, int gridsize) {
srand(time(NULL));
ship1.length = (int)((rand()) % gridsize) / 4 + 1;
ship1.location = (int)(rand()) % gridsize;
}
Anyway,in you case, using a member function maybe a better solution.
class ship {
public:
int location;
int length;
void createship(int gridsize) {
srand(time(NULL));
this->length = (int)((rand()) % gridsize) / 4 + 1;
this->location = (int)(rand()) % gridsize;
}
};
call:
ship1->createship(100);
You pass the ship by value, so the parameter createship gets is a copy of the original object and changing it won't change the original.
Pass a reference/pointer to ship and then changes to the parameter will change the original object.
Or much better, use a constructor.

C++ overloading == operator example

making chess game and i can't overload == operator (think that is problem, ofc if i added correctly elements in array).
enum squerState{EMPTY, ROOK, KNIGHT, BISHOP, QUEEN, KING, PAWN};
class Board
{
public:
Board();
~Board();
friend bool operator==(const Board& lhs, const Board& rhs);
squerState stanjePolja;
squerColor bojaPolja;
pieceColor bojaFigurice;
Board* board[8][8];
};
//.ccp
Board* piece;
for(int x= 0; x < 8; x++)
{
for(int y=0; y < 8; y++)
{
piece->stanjePolja = squerState::ROOK;
piece->bojaPolja = squerColor::WHITE;
piece->bojaFigurice = pieceColor::BLACK_PIECE;
board[y][x] = piece;
}
}
//overload ==
bool operator==(const Board& lhs, const Board& rhs)
{
return lhs.stanjePolja == rhs.stanjePolja;
}
//Draw test board
void Board::drawBoard()
{
for (auto y = 0; y < 8; y++)
{
for (auto x = 0; x < 8; x++)
{
if (board[y][x] == squerState::ROOK)
{
std::cout << 'O';
}
else
std::cout << 'X';
}
std::cout << std::endl;
}
}
Problem is when i try to draw test board with ROOK's.
if (board[y][x] == squerState::ROOK)
Thanks!
In the line
if (board[y][x] == squerState::ROOK)
it looks like the type of the expression on the left-hand side is Board*, but the type of expression on the right-hand side is enum squerState. You did not define an equals operator for those types and they can't be compared by other means.
You probably want your Board class to contain an array of SquareState instances.
enum Piece { None, Pawn, ... };
enum Color { Black, White };
struct SquareState
{
Piece piece_;
Color color_;
};
struct Board
{
void drawBoard() const;
SquareState board_[8][8];
};
void Board::drawBoard() const
{
for( int i = 0; i < 8; ++i )
{
for( int j = 0; j < 8; ++j )
{
switch( board_[ i ][ j ].piece_ )
{
case Piece::None:
std::cout << " ";
break;
case Piece::Pawn:
std::cout << "P";
break;
// ...
}
}
std::cout << std::endl;
}
}
I hope this helps.

Passing array to stringstream

This is something I had never noticed but for some reason you can't do something like
sstr << myarray;
If you do that "sstr" would contain the address of "myarray",You would have to do
for(int i;i < sizeof(myarray);i++)
{
sstr << myarray[i];
}
I would like to know why does this happens, I don't remember ever having to do that, but personally I think sometimes reality itself changes just to annoy me.
You need to define your own stream operation for an array to be able to display it.
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class mydata
{
public:
mydata(int size = 0) { for (int i = 0; i < size; i++) add(0); }
~mydata() { }
void add(T x) { data.push_back(x); }
void remove(int pos) { data.erase(data.begin() - pos); }
T& operator[](int pos) { return data[pos]; }
friend ostream& operator<<(ostream& os, const mydata<T>& name) {
for (int i = 0; i < x.data.size(); i++) os << x.data[i] << " "; return os; }
private:
vector<T> data;
};
That would be a standard class for encapsulating your data. If you wanted to do an operation like mydata<int> b(8); b[7] = 8; you can. The reason the code for the << operator is inside the class is because templates requires typename specific code to be inside the template itself.
Finally, this is how this code can be implemented.
int main()
{
mydata<char> charData;
mydata<int> intData;
for (int i = 0; i < 20; i++) {
charData.add(65+i);
intData.add(i);
}
cout << charData << endl;
cout << intData;
cin.get();
return 0;
}
The output looks like this:
A B C D E F G H I J K L M N O P Q R S T
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19