Passing array to stringstream - 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

Related

C++ Fix the following code so that it will correctly recursively traverse a directory tree in order to find where a particular file is

I have an assignment as following: Write a program will ask the user how many random numbers to generate. Then it will present a menu which has the options of Display, Average, Median, and Standard Deviation, Regenerate, and Quit. Without the use of a switch statement, or an if statements, or pointers to functions, have the program execute the user's selection from the menu. (Note: Function pointers are not allowed!)
This is what I have so far:
#include <iostream>
#include <cstdlib>
#include <array>
#include <cmath>
#include <stdlib.h>
#include <map>
using namespace std;
template <typename T> class wrapperclass
{
public:
static T myclass;
};
class Display
{
public:
static void myFunction(int random[], int num)
{
for(int i=0; i<num; ++i)
{
cout << random[i] <<endl;
}
}
};
class Average
{
public:
static double myFunction(int random[], int num)
{
double avg = 0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
return avg/num;
}
};
class Median
{
public:
static double myFunction(int random[], int num)
{
double mid = 0;
if(num % 2 == 0)
{
mid = (random[num/2] + random[num/2-1])/2;
}
else
{
mid = random[num/2];
}
return mid;
}
};
class StdDi
{
public:
static double myFunction(int random[], int num)
{
double avg=0;
double total=0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
avg = avg/num;
for(int i=0; i<num; ++i)
{
total += (avg-random[i])*(avg-random[i]);
}
total = total/num;
return sqrt(total);
}
};
class renerate
{
public:
static void myFunction(int)
{
}
};
class quit
{
public:
static void myFunction()
{
exit(EXIT_FAILURE);
}
};
int main()
{
int num = 0;
int option = 0;
map<int, class T> magic;
cout << "How many random numbers would u like to generate? " << endl;
cin >> num;
int random[num];
for(int i=0; i<num; ++i)
{
random[i] = rand() % 100 + 1;
}
cout << " Menu"<<endl
<< "1. Display"<<endl
<< "2. Average"<<endl
<< "3. Median"<<endl
<< "4. Standard Deviation"<<endl
<< "5. Renerate"<<endl
<< "6. Quit"<<endl;
cin >> option;
cout<<wrapperclass<Average>::myclass.myFunction(random, num);
return 0;
}
I'm about to directly pass the user input "option" into that "wrapperclass" like this "wrapperclass" so I can simply call the .myFunction since all classes have the same function name. but this won't work for c++ so is there any work around?

std::sort using member function in the same class?

I have a class "PclProc" and I want to use std::sort.
I write a compare function in the same class because this comparing need the "in_ptr" which is a variable in the same class.
But as I did as following, there is always an error:
error: no matching function for call to
‘sort(std::vector::iterator, std::vector::iterator,
)’
std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);
bool PclProc::MyCompare(int id1, int id2)
{
return in_ptr->points[id1].z<in_ptr->points[id2].z;
}
float PclProc::MedianZDist(pcl::PointIndices cloud_indice)
{
std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);
int size=cloud_indice.indices.size();
float median_x,median_y;
...
Example of a functor being used for std::sort. vector D is the data, vector I is the indices to D. I is sorted according to D with std::sort using the functor. std::sort only creates one instance of class lessthan, then uses that one instance for all of the compares.
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
typedef unsigned int uint32_t;
#define SIZE 16
class example{
public:
std::vector<uint32_t> D; // data
std::vector<uint32_t> I; // indices
example(void)
{
D.resize(SIZE);
I.resize(SIZE);
for(uint32_t i = 0; i < SIZE; i++){
D[i] = rand()%100;
I[i] = i;
}
}
void displaydata(void)
{
for(size_t i = 0; i < SIZE; i++)
std::cout << std::setw(3) << D[I[i]];
std::cout << std::endl;
}
class lessthan // lessthan functor for std::sort
{
public:
const example &x;
lessthan(const example &e ) : x(e) { }
bool operator()(const uint32_t & i0, const uint32_t & i1)
{
return x.D[i0] < x.D[i1];
}
};
void sortindices(void)
{
std::sort(I.begin(), I.end(), lessthan(*this));
}
};
int main()
{
example x;
x.displaydata();
x.sortindices();
x.displaydata();
return 0;
}

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.

how to print to screen a vector?

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;
}

Help to call overloaded insertion operator

I tried calling my overloaded inserter but it's not doing what it's supposed to do.
#include <iostream>
#include "SortedLinkedListInt.h"
#include <sstream>
using namespace std;
//CONSTRUCTOR
SortedLinkedListInt::SortedLinkedListInt(){
head = NULL;
size = 0;
}
//DESTRUCTOR
SortedLinkedListInt::~SortedLinkedListInt(){
while (head != NULL) {
Node* ptr = head;
head = head -> next;
delete ptr;
}
}
//COPY CONSTRUCTOR
SortedLinkedListInt::SortedLinkedListInt(const SortedLinkedListInt &obj){
for(Node* n = obj.head; n!=NULL; n=n->next)
add(n->data);
}
void SortedLinkedListInt::add(int newElement){
if (head == NULL){
head = new Node;
head->next = NULL;
head->data = (newElement);
}
else if(head->data > newElement){
Node* node1 = new Node;
node1->data = newElement;
node1->next = head;
head = node1;
}
else{
Node* node2;
for(node2=head; node2->next!= NULL; node2 = node2->next)
if(node2->next->data > newElement)
break;
Node* node = new Node;
node->next = (node2->next);
node->data = (newElement);
node2->next = (node);
++size;
}
}
bool SortedLinkedListInt::exists (int element){
for (Node* n = head; n != NULL; n = n -> next) // how to write n.getElement() in c++
if(element == n->data) //analogous to compareTo (java)
return true;
return false;
}
void SortedLinkedListInt::toString(){
for (Node* n = head; n != NULL; n = n->next){
cout << n->data << endl;
}
cout << "\n";
}
void SortedLinkedListInt::operator <<(const int &sub){
add(sub);
for (Node* n = head; n != NULL; n = n->next){
cout << n->data << endl;
}
cout << "\n";
}
The function is at the bottom of the above header file. Below is the main.cpp
#include <iostream>
#include "SortedLinkedListInt.h"
#include <cstdio>
using namespace std;
int main(){
SortedLinkedListInt *sll = new SortedLinkedListInt();
//SortedLinkedList <int> *sll = new SortedLinkedList<int>;
/*SortedLinkedList<int> sll2 = *sll;*/
sll->add(5);
sll->add(1);
sll->add(3);
sll->add(9);
sll->add(2);
sll->add(5);
cout << 5;
cout << 3;
//sll->toString();
int n = 4;
printf("%d does%s exist in list.\n", n, sll->exists(n) ? "": " not");
system("PAUSE");
}
cout << 5 or any number wont call the overloaded insertion operator. I wanted to have it do the same function as sll->(5). So instead of using sll->(x) all that will be done is cout << x;
I am not sure what you are trying to achieve but
cout << 5
calls the insertion operator of cout standard stream. If you want to call your own insertion operator at least left part of the statement must be your class.
I hope this helps.