The problem approaching private number of class - c++

My program receives width and breadth of rectangle
My output would be rectangle and specific point which can get from second line input. If number is odd , it will represent 'y' coordinate, else it will represent 'x' coordinate.
My problem is
pt.mark(pt.get_p(), pt.get_q());
this one.
In my method "mark",
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
x() represents " 0 " . So , my rectangle looks like
I don't know why this happen , because my approach to the private number of Class "Point" is not wrong using method x().
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <sstream>
using namespace std;
class Point
{
private:
int _x, _y;
public:
Point(int x=0, int y=0): _x(x), _y(y) {}
int x() { return _x; }
int x(int n) {return _x = n;}
int y() { return _y; }
int y(int n) {return _y=n;}
};
class MovingPoint: public Point
{
private:
int p, q;
vector<int> nums;
public:
MovingPoint(int x = 0, int y = 0): Point(x, y) {}
MovingPoint(vector<int> a) : nums(a) {}
void mark(int x, int y);
void calculate();
int get_p() {return p;}
int get_q() {return q;}
};
ostream& operator <<(ostream& out, MovingPoint p)
{
return out << "(" << p.x() << ", " << p.y() << ")";
}
void MovingPoint::mark(int a, int b)
{
ostringstream buf;
vector<int> lengths;
vector<string> words;
int cnt;
char prev = buf.fill('-');
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
char pres = buf.fill(' ');
for (int i = 0; i < y() ; i++)
{
if (i == b - 1)
buf << "| " << setw(a) << "." << setw(x() - a) << " |" << endl;
else
buf << "| " << setw(x()) << " |" << endl;
}
char prev1 = buf.fill('-');
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
buf.fill(prev1);
cout << buf.str();
}
void MovingPoint::calculate()
{
p = 0;
q = 0;
for (int i = 0; i < nums.size() ; i++)
{
if (nums[i] % 2 == 0)
p++;
else
q++;
}
}
int main()
{
int x;
int y;
vector<int> nums;
cin >> x >> y;
MovingPoint pt(x, y);
while (cin >> x)
{
nums.push_back(x);
}
pt = MovingPoint(nums);
pt.calculate();
pt.mark(pt.get_p(), pt.get_q());
}

You might do, with some renaming:
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <sstream>
struct Rectangle
{
unsigned int width;
unsigned int height;
};
struct Point
{
unsigned int x;
unsigned int y;
};
void draw(const Rectangle& rect, const Point& pt)
{
std::ostringstream buf;
buf.fill('-');
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
buf.fill(' ');
for (unsigned int i = 0; i < rect.height() ; i++)
{
if (i == pt.y - 1)
buf << "| " << setw(pt.x) << "." << setw(rect.width() - pt.x) << " |" << endl;
else
buf << "| " << setw(rect.width()) << " |" << endl;
}
char prev1 = buf.fill('-');
buf << "+-" << setw(rect.width() - 2) << "" << "-+" << endl;
buf.fill(prev1);
std::cout << buf.str();
}
Point calculate(const std::vector<int>& v)
{
Point p{0, 0};
for (auto e : v)
{
if (e % 2 == 0)
p.x++;
else
p.y++;
}
return p;
}
int main()
{
Rectangle r;
std::cin >> r.width >> r.height;
std::vector<int> nums;
int n;
while (std::cin >> n)
{
nums.push_back(n);
}
Point pt = calculate(nums);
draw(r, pt);
}

Related

How to format output like this

My code is like this so far :
void matrix::print(int colWidth) const
{
cout << getRows() << " x " << getCols() << endl;
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
for (unsigned x = 0; x < getRows(); x++) {
cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
cout << setw(colWidth) << at(x, y) << " |";
}
cout << endl;
}
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
}
But the output depends on the colWidth which will be the space between each number printed. So how can I adjust my dashes to be printed like the following no matter the colWidth it should align.
One output should look like this:
Second output is like this:
If the column width is a parameter, you're almost done with your code. Just turn the cout<<"--------" into:
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-');
That code prints a string of dashes, which width is: number of matrix columns, times column width plus 2, plus 1:
Plus 2 because you are appending a " |" to each column.
Plus 1 because you are adding a '|' at the beginning of each row.
You may want to check for empty matrices at the beginning of your print method.
[Demo]
#include <initializer_list>
#include <iomanip> // setw
#include <iostream> // cout
#include <vector>
class matrix
{
public:
matrix(std::initializer_list<std::vector<int>> l) : v{l} {}
size_t getRows() const { return v.size(); }
size_t getCols() const { if (v.size()) { return v[0].size(); } return 0; }
int at(size_t x, size_t y) const { return v.at(x).at(y); }
void print(int colWidth) const
{
std::cout << "Matrix: " << getRows() << " x " << getCols() << "\n";
// +2 due to " |", +1 due to initial '|'
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
for (unsigned x = 0; x < getRows(); x++) {
std::cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
std::cout << std::setw(colWidth) << at(x, y) << " |";
}
std::cout << "\n";
}
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
}
private:
std::vector<std::vector<int>> v{};
};
int main()
{
matrix m{{1, 2}, {-8'000, 100'000}, {400, 500}};
m.print(10);
}
// Outputs
//
// Matrix: 3 x 2
// -------------------------
// | 1 | 2 |
// | -8000 | 100000 |
// | 400 | 500 |
// -------------------------

Modifying "Const Char Pointers" in C++

I am doing a program to test swapping couple of things by reference.
I managed to get the first two functions in my code to work but can't get to change the char * in the third function.
I think the problem is that it's a constant and only valid to read-only
that's what the error is telling me but How to be able to work with it in this way?
Here is the code:
#include <iostream>
using namespace std;
void swapping(int &x, int &y)
{
int temp =x;
x=y;
y=temp;
}
void swapping(float &x, float &y)
{
float temp=x;
x=y;
y=temp;
}
void swapping(const char *&x,const char *&y)
{
int help = *x;
(*x)=(*y);
(*y)=help;
} // swap char pointers
int main(void) {
int a = 7, b = 15;
float x = 3.5, y = 9.2;
const char *str1 = "One";
const char *str2 = "Two";
cout << "a=" << a << ", b=" << b << endl;
cout << "x=" << x << ", y=" << y << endl;
cout << "str1=" << str1 << ", str2=" << str2 << endl;
swapping(a, b);
swapping(x, y);
swapping(str1, str2);
cout << "\n";
cout << "a=" << a << ", b=" << b << endl;
cout << "x=" << x << ", y=" << y << endl;
cout << "str1=" << str1 << ", str2=" << str2 << endl;
return 0;
}
As suggested in the comments:
void swapping(const char*& x, const char*& y)
{
auto t = x;
x = y;
y = t;
}
Now you should consider to use a template:
template<typename Type>
void swapping(Type& a, Type& b)
{
auto t = a;
a = b;
b = t;
}

C++ programming problem, failed to assign pointers to correct objects

I've been working on a problem which involves an size-N square matrix maze with N^2 nodes and 2N(N-1) edges connecting vertical and horizontal neighbours. The codes are as follows:
//Node.h
#pragma once
#define NULL 0
using namespace std;
class Edge;
class Node {
public:
int id, row, col;
Edge* EL, * ER, * EU, * ED;
vector<int> connected;
Node(int id, int row, int col);
Node* get_L();
Node* get_R();
Node* get_U();
Node* get_D();
void print();
};
//Edge.h
#pragma once
#include "Node.h"
class Edge {
public:
int id, type;
bool state;
Node* N1, * N2;
Edge(int id, Node n1, Node n2, int type);
void setState(bool b);
void print();
};
//Maze.h
#pragma once
#include <vector>
#include "Node.h"
#include "Edge.h"
using namespace std;
class Maze {
public:
int size;
vector<Node> nodes;
vector<Edge> edges;
Maze(int N);
void print();
};
//main.cpp
#include <iostream>
#include <vector>
#include "Node.h"
#include "Edge.h"
#include "Maze.h"
Node::Node(int id, int row, int col) {
this->id = id;
this->row = row;
this->col = col;
this->EL = NULL;
this->ER = NULL;
this->EU = NULL;
this->ED = NULL;
}
Node* Node::get_L() {
if (EL) {
return EL->N1;
}
else {
cerr << "Node " << id << "does not have left neighbour.";
}
}
Node* Node::get_R() {
if (ER) {
return ER->N2;
}
else {
cerr << "Node " << id << "does not have right neighbour.";
}
}
Node* Node::get_U() {
if (EU) {
return EU->N1;
}
else {
cerr << "Node " << id << "does not have up neighbour.";
}
}
Node* Node::get_D() {
if (ED) {
return ED->N2;
}
else {
cerr << "Node " << id << "does not have down neighbour.";
}
}
void Node::print() {
int l, r, u, d;
l = EL ? EL->N1->id : -1;
r = ER ? ER->N2->id : -1;
u = EU ? EU->N1->id : -1;
d = ED ? ED->N2->id : -1;
cout << "Node " << id << " (Row " << row << " Col " << col << "), neighbours <L,R,U,D>: <" << l << "," << r << "," << u << "," << d << ">" << endl;
}
Edge::Edge(int id, Node n1, Node n2, int type) {
this->id = id;
this->N1 = &n1;
this->N2 = &n2;
this->state = false;
this->type = type;
}
void Edge::print() {
if (type == 0) {
cout << "Horizontal ";
}
else {
cout << "Vertical ";
}
cout << "edge " << id << " between <" << N1->id << ", " << N2->id << ">, " << state << endl;
}
void Edge::setState(bool b) {
this->state = b;
}
Maze::Maze(int N) {
size = N;
for (int i = 0; i < N * N; ++i) {
Node n = Node(i, i / N, i % N);
nodes.push_back(n);
}
int eid = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N - 1; ++j) {
Node n1 = nodes[i * N + j];
Node n2 = nodes[i * N + j + 1];
Edge e = Edge(eid, n1, n2, 0);
/*
// &n1 and &n2 retain the same throughout the loop
cout << &n1 << endl;
cout << &n2 << endl;
cout << e.N1->id << "," << e.N2->id << endl; // This line gives correct result
e.print(); // Incorrect
*/
n1.ER = &e;
n2.EL = &e;
edges.push_back(e);
eid++;
}
}
cout << nodes[0].ER << endl;
for (int i = 0; i < N - 1; ++i) {
for (int j = 0; j < N; ++j) {
Node n1 = nodes[i * N + j];
Node n2 = nodes[i * N + j + 1];
Edge e = Edge(eid, n1, n2, 1);
n1.ED = &e;
n2.EU = &e;
edges.push_back(e);
eid++;
}
}
}
void Maze::print() {
cout << size << " x " << size << " Maze" << endl;
cout << nodes.size() << " nodes:" << endl;
for (auto& i : nodes) {
i.print();
}
cout << edges.size() << " edges:" << endl;
for (auto& i : edges) {
i.print();
}
}
int main()
{
Maze m = Maze(8);
m.print();
}
However after compiling and running I found out that the nodes and edges are NOT connected to each other as I expected. In the codes of creating edges I tried to figure out the reason (see the commented part), I found that in the entire loop, the addresses of n1 and n2 always retain the same. Still have no idea why this is happening. Please help.

How do I switch this to unique_ptr?

How do I make it so I dont have to manually delete the pointer?
With unique_ptr in the vector<> ?
Here is my code:
class vec2 {
public:
double x;
double y;
vec2() {
x = 0.0;
y = 0.0;
}
vec2(double xx, double yy) {
x = xx;
y = yy;
cout << "constructor called" << endl;
}
~vec2() {
static int count = 0;
cout << "destructor " << count << endl;
count++;
}
virtual double Length() { return sqrt(x * x + y * y); }
bool operator==(vec2& v) { return x == v.x && y == v.y; }
virtual string toString() {
stringstream s("");
s << "[" << x << " " << y << "]";
return s.str();
}
};
int main() {
vector<vec2*> vecs;
vecs.push_back(new vec2(1.8, 1.7));
vecs.push_back(new vec2(1.99, 1.7));
for (vec2* v : vecs) {
cout << v->toString() << endl;
delete v;
}
}
http://www.xgdev.com/notepad/textfiles/37631a.txt
Simple:
std::vector<std::unique_ptr<vec2>> vecs;
vecs.reserve(2); // Optional
vecs.push_back(std::make_unique<vec2>(1.8 ,1.7));
vecs.push_back(std::make_unique<vec2>(1.99, 1.7));
for (auto& v : vecs) {
cout << v->toString() << endl;
}
If you have virtual member function(s), most probably, destructor should also be virtual.

C++: transfer a vector into a subprogram

In my example there are three similar vectors which I would like to print.
Could you help me understand how to transfer a vector into a subprogram so that not to
repeat myself?
#include "stdafx.h";
#include <vector>;
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
struct SPoint
{
int X;
int Y;
};
vector<SPoint> points;
vector<SPoint> selected;
vector<SPoint> cleared;
void print_points()
{
cout << "Points: "<< endl;
for (int i = 0; i < points.size(); i++)
{
cout << '('<<points[i].X <<',' <<points[i].Y <<')'<< endl;
}
cout << endl;
}
void print_selected()
{
cout << "Selected: "<< endl;
for (int i = 0; i < selected.size(); i++)
{
cout << '('<<selected[i].X <<',' <<selected[i].Y <<')'<< endl;
}
cout << endl;
}
void print_cleared()
{
cout << "Cleared: "<< endl;
for (int i = 0; i < cleared.size(); i++)
{
cout << '('<<cleared[i].X <<',' <<cleared[i].Y <<')'<< endl;
}
cout << endl;
}
int main ()
{
SPoint temp = {0, 0};
for (int i = 0; i < 11;i++)
{
temp.X = i;
temp.Y = i;
points.push_back(temp);
}
for (int i = 5; i< 11;i++)
{
temp.X = i;
temp.Y = i;
points.push_back(temp);
}
print_points();
print_selected();
print_cleared();
system ("pause");
return 0;
}
You could do something like this:
void
print(const std::vector<SPoint>& vect, const std::string& message)
{
std::cout << message << ":" << std::endl;
for (int i = 0, size = vect.size(); i < size; ++i)
std::cout << vect[i].X << ":" << vector[i].Y << " ";
std::endl;
}
print(points, "Points");
print(points, "Selected");
print(points, "Cleared");
Good luck
To pass a vector as an argument to a function you do something like this:
void func(const vector<SPoint>& points) {
... do stuff
}
Then you call the function in you code like this:
...some stuff
vector<SPoint> a;
func(a);
Just use a const reference to a vector and pass it to the function:
void print(const vector<SPoint> &data) const {
}
...
print(points);
Here is a full C++ style approach:
struct SPoint
{
int X;
int Y;
};
std::ostream& operator <<( std::ostream& stream, SPoint const& point )
{
stream << '(' << point.X << ',' <<point.Y << ')';
return stream;
}
void print_vector( std::ostream& stream, std::vector< SPoint > const& vector )
{
std::copy(
points.begin(), points.end()
, std::ostream_iterator< SPoint >( std::cout, '\n' )
);
}
and then:
print_vector( std::cout, points );
print_vector( std::cout, selected );
print_vector( std::cout, cleared );