How to use c++ structure array like flexible? - c++

What should I do if I want to use the structure array flexibly?
I made my code like below, and tried Triangle and Rectangular..
Triangle was success but when i tried Rectangular I got error messages.
struct C2D {
double x, y;
};
class Polygon {
int point;
std::vector<C2D> arr;
public:
Polygon(int point_, C2D arr_[]) : arr(point_) {
point = point_;
memcpy(arr.data(), arr_, sizeof(C2D) * point);
};
void print() const {
for (int i = 0; i < point; i++) {
cout << arr[i].x << " " << arr[i].y << endl;
}
};
};
int main() {
int point;
C2D c2d[3];
cout << "point : ";
cin >> point;
cout << endl;
vector<C2D>c2d(point);
for (int i = 0; i < point; i++) {
cout << i + 1 << "x : ";
cin >> c2d[i].x;
cout << i + 1 << "y : ";
cin >> c2d[i].y;
cout << endl;
}
cout << endl;
Polygon p(point, c2d);
p.print();
return 0;
}

The problem is that you use the same name for
C2D c2d[3];
and
vector<C2D>c2d(point);
However, your code has several other issues such as using C-arrays in C++. Consider using std::vector, e.g., like this:
#include <iostream>
#include <vector>
struct C2D {
double x, y;
};
class Polygon {
std::vector<C2D> coordinates;
public:
explicit Polygon(const std::vector<C2D> &coords) : coordinates(coords) {}
void print() const {
for (const auto &c : coordinates) {
std::cout << c.x << " " << c.y << "\n";
}
}
};
int main() {
int point;
std::cout << "point : ";
std::cin >> point;
std::cout << "\n";
std::vector<C2D> coordinates(point);
for (int i = 0; i < point; i++) {
std::cout << i + 1 << "x : ";
std::cin >> coordinates[i].x;
std::cout << i + 1 << "y : ";
std::cin >> coordinates[i].y;
std::cout << "\n";
}
std::cout << "\n";
Polygon p(coordinates);
p.print();
}

As per your code, you declared variable name c2d one is C2D array type and the other is a vector of C2D what is the purpose of two variable names are the same you declared. My suggestion is to allocate c2d variable based on point count and pass to the polygon. As per my understanding change your polygon constructor with parameter array or vector and passing the corresponding argument to the constructor.

Related

How I get center of points?

Problem: Create a vector consisting of point objects in a two-dimensional plane, calculate the average of the x and y coordinates of the point objects, and write a program that outputs the center of the points.
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
class Point
{
public:
Point(std::string pname = NULL, int px = 0, int py = 0)
{
setName(pname); setX(px); setY(py);
}
std::string getName() { return name; }
int getX() { return x; }
int getY() { return y; }
void setName(std::string pname) { name = pname; }
void setX(int px) { x = px; }
void setY(int py) { y = py; }
private:
std::string name;
int x;
int y;
};
int main()
{
int a;
int counter = 0;
cout << "number of points" << endl;
cin >> a;
vector<Point> v1(a);
while (counter < a)
{
Point p1;
string tmp;
int tmp_x;
int tmp_y;
cout << "name of point" << endl;
cin >> tmp;
p1.setName(tmp);
cout << "position of point" << endl;
cin >> tmp_x >> tmp_y;
p1.setX(tmp_x);
p1.setY(tmp_y);
v1.push_back(p1);
cout << p1.getName() <<p1.getX() << p1.getY() << endl;
}
return 0;
}
this is an example of what I want (inline is keyboard input)
Number of points: 2
Name of point: p1
position of a point: 10 20
p1 (10, 20)
Name of point: p2
position of a point: 40 50
p2 (40, 50)
centor of points :(25.0, 35.0)
How should I approach averaging?
You don't need all of those #includes.
Pay attention to NULL in class constructor.
Loop continuation condition: a--. Variable counter is redundant.
Vector is dynamic data structure. You don't need to declare its size explicitly, in this exercise. Member-function push_back will do dirty work for you.
One more extra variable p1. Try:
v1.push_back( { tmp, tmp_x, tmp_y } );
Finally...
double // if precision is necessary
total_x{}, total_y{};
for ( auto& point : v1 ) {
total_x += point.getX();
total_y += point.getY();
}
std::cout << "Average X: " << total_x / v1.size()
<< "\nAverage Y: " << total_y / v1.size();
return EXIT_SUCCESS;

Clarification about function calls in cout needed

i'm doing an online c++ learning course with quiz. The last output line of this snippet is to be determined (comments added by me). Correct answer: 10. My question: why 10 and not 11?
Calling a(b) swaps the two variables, so why is the last a.a.b 0 and not 1? / Why does the a.b() in cout not affect the a.a.b?
#include <iostream>
using namespace std;
class classA {
public:
classA() { st.f = st.p = 1; }
struct { int f, p; } st;
int bfunc(void);
};
int classA::bfunc(void) { int x = st.f; st.f = st.p; st.p = x; return x; };
int main()
{
classA a;
a.st.f = 0;
cout << a.st.f << a.st.p << endl; //01
a.bfunc();
cout << a.st.f << a.st.p << endl; //10
a.bfunc();
cout << a.st.f << a.st.p << endl; //01
a.bfunc();
cout << a.st.f << a.st.p << endl; //10
cout << a.bfunc() << a.st.p << endl; //10
return 0;
}

The problem approaching private number of class

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

List in C++ Standard Template Library (STL). I made the following program and I don't know how to make a function to print the list

#include <iostream>
#include <list>
#include <iterator>
using namespace std;
class Profesor
{
public:
string nume, departament;
int grad, vechime;
Profesor(string n, string d, int g, int v);
};
Profesor::Profesor(string n, string d, int g, int v) {
nume = n;
departament = d;
grad = g;
vechime = v;
}
int main()
{
list <Profesor*> profi;
Profesor* p;
int opt;
string nume, departament;
int grad, vechime;
do {
cout << "1.Adaugare" << endl;
cout << "Dati optiunea! " << endl;
cin >> opt;
switch (opt)
{
case 1:
cout << "Nume:";
cin >> nume;
cout << "Departament:";
cin >> departament;
cout << "Grad:";
cin >> grad;
cout << "Vechime";
cin >> vechime;
p = new Profesor(nume, departament, grad, vechime);
profi.push_front(p);
default:
break;
}
} while (opt);
return 0;
}
Option 1 is to add a new item into the list
This is the constructor of the class
So I need a function to display the entire list
ajgnsjdgn afkajkf nskjfnakfakfnaf afnakfnasdnlang akfnafdakfrnaasf asdfkasfna
ad akjdgnakjsgsa askfnaksd asgnaskdng asdgjnsadgag
Add a function to Profesor to output it's current variables:
void output() const {
cout << " * nume: " << nume << endl;
cout << " * departament: " << departament << endl;
cout << " * grad: " << grad << endl;
cout << " * vechime: " << vechime << endl;
}
Create a function that iterates through the list and calls this function.
Here is an example that uses a range based for loop:
void outputProfesors(const list<Profesor*>& profesors) {
for (const auto& profesor : profesors) {
profesor->output();
}
}
Call outputProfesors().

Pass reference of array of objects to function

I'm trying to change a parameter of an object inside an array, but it seems like it's creating a new one when I pass it to the function.
I already saw similar questions and answers like this one, but it doesn't work for me, because I don't have a fixed array size in the final code.
I created a very short version of the code to show the problem.
#include <iostream>
using namespace std;
class Vect {
public:
Vect(int x, int y)
{
_x = x;
_y = y;
}
int _x;
int _y;
};
void ChangeX(Vect tests[], int size)
{
for (int i = 0; i < size; i++) {
tests[i]._x = 39;
}
}
int main()
{
Vect v1 = Vect(1,2);
Vect v2 = Vect(6,3);
cout << "Initial X: ";
cout << v1._x;
cout << "\n";
Vect vectors[2] = { v1, v2 };
cout << "Final X: ";
ChangeX(vectors, 2);
cout << v1._x;
return 0;
}
I expect the output to be:
Initial X: 1
Final X: 39
But in reality is:
Initial X: 1
Final X: 1
Also, using C++ vectors is not the solution for now. I'm running low on program memory usage and have a very small space for extra code.
Your issue has nothing to do with your function. It is updating the contents of the array correctly. There is no need to pass the array itself by reference.
The real problem is with the array itself. The statement Vect vectors[2] = {v1, v2}; makes copies of the v1 and v2 objects in the array. Your function is modifying the copies, and then afterwards you output values from the originals instead of the copies. So, your output does not change, since the function is not modifying the originals.
To accomplish what you are attempting, pass in an array of pointers instead, where the pointers are pointing at the original objects, not copies of them, eg:
#include <iostream>
class Vect {
public:
Vect(int x, int y){
_x = x;
_y = y;
};
int _x;
int _y;
};
void ChangeX(Vect* tests[], int size){
for(int i = 0; i < size; i++){
tests[i]->_x = 39;
}
}
int main()
{
Vect v1(1,2);
Vect v2(6,3);
std::cout << "Initial X:\n";
std::cout << v1._x << "\n";
std::cout << v2._x << "\n";
Vect* vectors[2] = {&v1, &v2};
ChangeX(vectors, 2);
std::cout << "Final X:\n";
std::cout << v1._x << "\n";
std::cout << v2._x << "\n";
return 0;
}
Live Demo
Otherwise, start out with an array to begin with, eg:
#include <iostream>
class Vect {
public:
Vect(int x, int y){
_x = x;
_y = y;
};
int _x;
int _y;
};
void ChangeX(Vect tests[], int size){
for(int i = 0; i < size; i++){
tests[i]._x = 39;
}
}
int main()
{
Vect vectors[2] = {Vect(1,2), Vect(6,3)};
std::cout << "Initial X:\n";
std::cout << vectors[0]._x << "\n";
std::cout << vectors[1]._x << "\n";
ChangeX(vectors, 2);
std::cout << "Final X:\n";
std::cout << vectors[0]._x << "\n";
std::cout << vectors[1]._x << "\n";
return 0;
}
Live Demo