I'm trying to write a code that creates a rectangle class and also create two classes which compare the perimeter and the area of two rectangles and return the larger of the two. I keep getting errors that there is an expected ';' in places which I don't think they belong. Any suggestions?
#include <cstdlib>
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
template <typename Object, typename Comparator>
const Object & findMax( const vector<Object> & arr, Comparator isLessThan )
{
int maxIndex = 0;
for( int i = 1; i < arr.size(); ++i )
if( isLessThan( arr[ maxIndex], arr[ i ] ) )
maxIndex = i;
return arr[ maxIndex ];
}
class AreaComparator
{
public:
int compare( Rectangle lhs, Rectangle rhs ) const
{ return double.compare( lhs.getArea(), rhs.getArea() ); }
};
class PeriComparator
{
public:
int compare( Rectangle lhs, Rectangle rhs ) const
{ return double.compare( lhs.getPerimeter(), rhs.getPerimeter() ); }
};
class Rectangle
{
double length, width;
public:
Rectangle( double l, double w)
{
l = length;
w = width;
}
double getArea()
{
return length * width;
}
double getPerimeter()
{
return ( 2 * length) + ( 2 * width );
}
};
int main(int argc, char *argv[])
{
cout <<(findMax(new Rectangle[] { new Rectangle(1, 5), new Rectangle(2, 3) }, new AreaComparator())) << endl;
cout <<(findMax(new Rectangle[] { new Rectangle(1, 5), new Rectangle(2, 3) }, new PeriComparator())) << endl;
system("PAUSE");
delete Rectangle[];
delete AreaComparator[];
delete PeriComparator[];
return EXIT_SUCCESS;
}
Any suggestions?
Building on #Logicrat's comment, I would suggest assigning all your new objects to local variable names, and then splitting up your cout statements into shorter pieces (multiple short cout's replacing each long cout). If the ; problem persists, you will more easily see why.
Related
class enemy{
....
}
std::vector<std::unique_ptr<enemy> > enemies1;
for (unsigned i = 0; i < 3; ++i)
enemies1.emplace_back(...);
for (int i = 0; i < enemies1.size(); i++) {
std::cout << i <<"x: " << enemies1[i]->rect.getPosition().x << std::endl;
}
output:
100
200
400
How could I get the minimum coordinate value from multiple enemies in the vector? I want to detect the nearest enemy from the player, eg the player's coordinate is 50 and enemies are at 100, 200, 400, as you see in the above example. I want to detect the nearest enemy in the vector.
You can use min_element from
#include <algorithm>
#include <iostream>
#include <vector>
struct enemy_t
{
explicit enemy_t(const double d) :
distance{ d }
{
}
double distance;
};
int main()
{
// create a vector of enemies using the constructor with one double
std::vector<enemy_t> enemies{ 100.0,400.0,200.0,10.0 };
// the last argument to min_element is a lambda function
// it helps you define by what condition you want to find your element.
auto enemy = std::min_element(enemies.begin(), enemies.end(), [](const enemy_t& lhs, const enemy_t& rhs)
{
return lhs.distance < rhs.distance;
});
std::cout << "The minimum distance found = " << enemy->distance << "\n";
return 0;
}
For finding out the minimum you can use :
auto result = std::min_element(enemies.begin(), enemies.end(), [](auto a, auto b){return a->rect.getPosition()< b->rect.getPosition();});
std::cout<<"minimum is: "<<(**result).rect.getPosition()<<std::endl;
The above example will print out the position of the closest(minimum) enemy as you want. You just need to add the above two statements into your program.
To confirm that this works(compile and gives the expected result), below i have given an example whose output can be seen here.
#include <vector>
#include <iostream>
#include <algorithm>
struct Rectangle
{
int getPosition() const
{
return position;
}
Rectangle(int p):position(p)
{
}
int position = 0;
};
struct enemy
{
Rectangle rect;
enemy(int p): rect{p}
{
}
};
int main()
{
std::vector<enemy*> enemies;
enemy e1(600),e2(200),e3(400),e4(300), e5(100);
enemies.push_back(&e1);
enemies.push_back(&e2);
enemies.push_back(&e3);
enemies.push_back(&e4);
enemies.push_back(&e5);
auto result = std::min_element(enemies.begin(), enemies.end(), [](auto a, auto b){return a->rect.getPosition()< b->rect.getPosition();});
std::cout<<"minimum is: "<<(**result).rect.getPosition()<<std::endl;
return 0;
}
I'd like to access a public variable of a class instance, where the instances are kept in a vector of the class type. I have to run through all elements of vector using an iterator, but it confuses me as to how I get the variables with the iterator present. I'm using C++98.
source.cpp:
#include <iostream>
#include <vector>
#include "Rectangle.h"
using namespace std;
int main() {
int len = 2, hen = 5;
int len2 = 4, hen2 = 10;
Rectangle rect1(len, hen);
Rectangle rect2(len2, hen2);
vector<Rectangle> Rects;
Rects.push_back(rect1);
Rects.push_back(rect2);
for (std::vector<Rectangle>::iterator it = Rects.begin(); it != Rects.end(); ++it) {
//how to access length and height here?
}
system("pause");
return 0;
}
Rectangle.h:
#pragma once
class Rectangle
{
private:
public:
int length;
int height;
Rectangle(int& length, int& height);
~Rectangle();
};
Rectangle.cpp:
#include "Rectangle.h"
Rectangle::Rectangle(int& length, int& height)
: length(length), height(height)
{ }
Rectangle::~Rectangle() {}
Add the rectangle to vector first, dereference iterator and access the elements.
int main() {
int len = 2, hen = 5;
int len2 = 4, hen2 = 10;
Rectangle rect1(len, hen);
Rectangle rect2(len2, hen2);
vector<Rectangle> Rects;
Rects.push_back(rect1);
Rects.push_back(rect2);
for (std::vector<Rectangle>::iterator it = Rects.begin(); it != Rects.end(); ++it) {
std::cout << "length " <<(*it).length<<std::endl;
std::cout << "height " <<(*it).height<<std::endl;
}
system("pause");
return 0;
}
Recently I've been trying to write a neural network program. I have all a neurons connections stored in a vector in the neuron. However whenever I push back a connection into the vector it doesn't seem to store (I can tell via debug mode), and when I try to add up the activation values of the vectors in a for loop, I get an out_of_range error. Here's my code.
Main.cpp
#include <iostream>
#include "neuron.h"
void displayboard(bool board [8][8]);
using namespace std;
int main()
{
int id = 2;
int inputids [] = {3};
int outputids [] = {4};
int inputweights [] = {5};
bool new_neuron = true;
neuron test (inputids, outputids, inputweights, new_neuron, id);
test.connections.at(0).value = 6;
// here is where the error is returned
test.activation();
cout << test.activationnumber;
return 0;
}
And here's Neuron.cpp:
#include "neuron.h"
#include <vector>
#include <random>
#include <ctime>
using namespace std;
neuron::neuron(int inputids [], int outputids [], int inputweights [],
bool new_neuron, int id)
{
this->id = id;
if (new_neuron==true) {
srand (time(0));
connection tempconnection;
for (int i = 0; i <=(sizeof (inputids)/sizeof (inputids [0])); i++)
{
tempconnection.type=false;
tempconnection.tofrom = inputids [i];
tempconnection.weight = rand ();
this->connections.push_back (tempconnection);
}
// this continues on for other options
}
void neuron::activation (){
for (int i=0; i<=this->connections.size (); i++) {
this->activationnumber += ((this->connections.at(i).value)
*(this->connections.at (i).weight));
}
}
UPDATE: Reading this will help you understand why your "sizeof/sizeof" approach is not good in C++.
Original answer
The behavior of sizeof(array)/sizeof(array[0]) might not be what you expected. The following code outputs 2 but you seem to expect 4. Use array for objects in the stack or vector for objects in the heap.
#include <iostream>
using namespace std;
void foo( int array[] )
{
wcout << sizeof( array ) / sizeof( array[ 0 ] );
}
int main()
{
int test[ 4 ];
foo( test );
return 0;
}
Change
int inputids [] = {3};
int outputids [] = {4};
to
vector< int > {3};
vector< int > {4};
Also change
neuron(int inputids [],int outputids [] …
{
…
for (int i = 0; i <= …; i++)
…
tempconnection.tofrom = inputids [i];
to
neuron( vector< int > & inputids, vector< int > & outputids …
{
…
for( auto id : inputids )
…
tempconnection.tofrom = id;
#include<iostream>
using namespace std;
class Array {
private:
int * data;
int size;
int isValidIndex();
public:
Array ( )
{
data = 0;
size = 0;
}
Array ( int );
Array (const Array &);
Array & operator = ( const Array & );
int & operator [] ( int );
void reSize(int);
~Array();
};
class CMatrix
{
private:
int * * data;
int row;
int col;
//isValidBounds( int , int );
public:
CMatrix ( )
{
data = 0;
row = col = 0;
}
CMatrix ( int r, int c );
CMatrix ( const CMatrix & );
CMatrix & operator = ( const CMatrix & );
//many other functions
};
//Do you feel suitable to implement operator ‘[]’ for class ‘CMatrix’ such that we should be able to manipulate them as follows, If yes then give the definition of operator ‘[]’ for ‘CMatrix’, otherwise given reason (solid/pinpoint) for not implementing this operator.
main()
{
CMatrix m(3,4); //3 by 4 matrix where ist row/col index is 0
m[1][2] = 67;
cout << m[1][2]; //should display 67
}
Basically I'm trying to compile a template class which is meant to represent a table for adding up polynomials. As a result of this the table needs to be nullable.
This is the sort of thing I am trying to represent http://www.mathsisfun.com/algebra/polynomials-adding-subtracting.html.
And this is the template which is meant to do it:
template <class T> class TableWithBlanks : public Table<T> {
public:
TableWithBlanks( const int width, const int height ) : w(width), h(height), table_contents( new t_node[width][height]
{
table_contents = new t_node[width][height];
// Go through all the values and blank them.
for( int i = 0; i < w; i++)
{
for( int a = 0; a < h; a++)
{
table_contents[i][a].value_ptr = NULL;
}
}
}
void set_value( const int width, const int height, const T* table_value_ptr)
{
if( width <= w && height <= h )
{
table_contents[w][h] = table_value_ptr;
}
}
T* get_value( const int width, const int height)
{
if( width <= w && height <= h )
{
return table_contents[width][height];
}
}
private:
typedef struct node {
T* value_ptr;
} t_node;
t_node** table_contents;
int w;
int h;
};
And this is the error I am getting:
[C++ Error] TableWithBlanks.h(16):
E2034 Cannot convert
'TableWithBlanks::node
( *)[1]' to
'TableWithBlanks::node
* *'
The PolynomialNode class is a class which is a linked list, where each node in the list represent the terms in a simple polynomial - I don't need to go into details.
In this line, you're trying to dynamically construct a two-dimensional array:
table_contents = new t_node[width][height];
but C++ doesn't work this way. For an example of how to allocate two-dimensional arrays, see this question, for example.