everyone if someone can help me I'll be very grateful.
I've been trying to fill in the structure called m_Center by a function of the same class, I'm using eclipse to work and it gave the next errors messages:
-'m_Center' was not declared in this scope
-Field 'radius' could not be resolved
-Symbol 'm_Center' could not be resolved
My header file is Obstacles.h:
#ifndef SRC_OBSTACLES_H_
#define SRC_OBSTACLES_H_
#include <eigen3/Eigen/Dense>
#include <iostream>
#include <random>
#include <list>
#include <stdlib.h>
#include <time.h>
class CObstacles
{
protected:
struct Center
{
float m_vXdCenterX;
float m_vXdCenterY;
float m_vXdCenterZ;
double distance;
Eigen::VectorXf v_XfAxisCyl;
Eigen::VectorXf vXfP1;
double radius;
};
Center m_Center;
public:
CObstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles);
~CObstacles();
void generate_obstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles);
};
#endif
while the Obstacles.cpp is:
#include "Obstacles.h"
CObstacles::CObstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles)
{
double m_dradius = dradius;
Eigen::VectorXf m_dvXdMaxBound = m_vXdMaxBound;
Eigen::VectorXf m_dvXdMinBound = m_vXdMinBound;
int dnum_obstacles = num_obstacles;
}
CObstacles::~CObstacles()
{
}
void generate_obstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles)
{
srand(time(NULL));
float aux_centerx, aux_centery;
Eigen::Vector3f vXfP1;
Eigen::Vector3f vXfP2;
Eigen::Vector3f distance;
for(int num_obs = 0; num_obs < num_obstacles; num_obs++)
{
aux_centerx = rand() % 20 + 1;
aux_centery = rand() % 20 + 1;
vXfP2 << aux_centerx, aux_centery, 0;
vXfP1 << aux_centerx, aux_centery, 0;
distance = vXfP2 - vXfP1;
m_Center[num_obs].radius = dradius;
}
}
Add the class name before the generate_obstacles method.
void CObstacles::generate_obstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles)
{
...
}
Related
I have a function that takes 2d-vector and outputs a 2d-vector. For some reason, the function is not getting called.
Here is the link to reproduce the issue: Google Colab.
In the link to check for correctness, I have added another code that uses the exact same function but doesn't take a 2d-vector array as an argument instead it runs on static input.
mycode.cpp:
#include <vector>
#include "geomutils.h"
#include "mycode.h"
#include <iostream>
using namespace std;
vector< vector<double> > customComputeConvexHull(vector< vector<double> > i_matrix){
cout <<"\nDone1.1";
Polygon custompts, customhull;
for (int r = 0; r < i_matrix.size(); r++){
custompts.push_back(Point(i_matrix[r][0], i_matrix[r][1]));
}
computeConvexHull(custompts, customhull);
// vector< vector<double> > res;
vector<vector<double>> res( customhull.size() , vector<double> (2));
for(int i = 0;i < customhull.size();i ++) {
res[i][0] = customhull[i].x;
res[i][1] = customhull[i].y;
}
return res;
}
void print_polygon(Polygon &h, int name){
std::cout << "\nHull in "<< name << ": \n"<<"[";
for(int i = 0;i < h.size();i ++) {
std::cout << "("<< h[i].x<< ", "<< h[i].y<<"), ";
}
std::cout <<"]\n";
}
void get_convex_hull_custom(){
Polygon custompts;
Polygon customhull;
custompts.push_back(Point(0,0));
custompts.push_back(Point(4.58,7.14));
custompts.push_back(Point(0,7.14));
computeConvexHull(custompts, customhull);
print_polygon(customhull, -99999);
}
int main()
{
// Create an empty vector
vector< vector<double> > mat,mat2;
vector<double> myRow1(0,0);
mat.push_back(myRow1);
vector<double> myRow2(7.61,9.48);
mat.push_back(myRow2);
vector<double> myRow3(0,9.48);
mat.push_back(myRow3);
cout <<"Done1\n";
get_convex_hull_custom();
mat2 = customComputeConvexHull(mat);
cout <<"Done2";
return 0;
}
mycode.h:
#ifndef _code
#define _code
#include <vector>
std::vector< std::vector<double> > customComputeConvexHull (std::vector< std::vector<double> > i_matrix);
#endif
geomutils.cpp:
#include "geomutils.h"
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
void computeConvexHull(Polygon &pts, Polygon &chull) {
chull.clear();
if(pts.size() == 1) {
chull.push_back(pts[0]);
chull.push_back(pts[0]);
return;
} else if(pts.size() == 2) {
chull.push_back(pts[0]);
chull.push_back(pts[1]);
chull.push_back(pts[0]);
return;
}
typedef boost::tuple<double, double> point;
typedef boost::geometry::model::multi_point<point> mpoints;
typedef boost::geometry::model::polygon<point> polygon;
mpoints mpts;
for(int i = 0;i < pts.size();i ++) {
boost::geometry::append(mpts,point(pts[i].x,pts[i].y));
}
polygon hull;
// Polygon is closed
boost::geometry::convex_hull(mpts, hull);
for(auto pt : hull.outer()) {
chull.push_back(Point(pt.get<0>(), pt.get<1>()));
}
}
geomutils.h:
#ifndef GEOMUTILS_H
#define GEOMUTILS_H
#include <vector>
struct Point {
double x,y;
Point(){}
Point(double x, double y):x(x),y(y){}
};
typedef std::vector<Point> Polygon;
void computeConvexHull(Polygon &pts, Polygon &chull);
#endif // GEOMUTILS_H
When I compile the code and try to run it.
Only Done1 gets printed on the console. It neither gives any error nor any message.
Output:
Done1
Hull in -99999:
[(0, 0), (0, 7.14), (4.58, 7.14), (0, 0), ]
There's some issue on your code. First of all in main to correctly initialize the vector you have to use the {} syntax. Further in customComputeConvexHull you are setting values inside the res vector which are not yet present. You have to use push_back to populate res. Below a version of your code which works (I put everything into one cpp file for semplicity.
#include <vector>
//#include "geomutils.h"
//#include "mycode.h"
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
using namespace std;
struct Point {
double x, y;
Point() {}
Point(double x, double y) :x(x), y(y) {}
};
typedef std::vector<Point> Polygon;
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian);
void computeConvexHull(Polygon& pts, Polygon& chull) {
chull.clear();
if (pts.size() == 1) {
chull.push_back(pts[0]);
chull.push_back(pts[0]);
return;
}
else if (pts.size() == 2) {
chull.push_back(pts[0]);
chull.push_back(pts[1]);
chull.push_back(pts[0]);
return;
}
typedef boost::tuple<double, double> point;
typedef boost::geometry::model::multi_point<point> mpoints;
typedef boost::geometry::model::polygon<point> polygon;
mpoints mpts;
for (int i = 0; i < pts.size(); i++) {
boost::geometry::append(mpts, point(pts[i].x, pts[i].y));
}
polygon hull;
// Polygon is closed
boost::geometry::convex_hull(mpts, hull);
for (auto pt : hull.outer()) {
chull.push_back(Point(pt.get<0>(), pt.get<1>()));
}
}
vector< vector<double> > customComputeConvexHull(vector< vector<double> > i_matrix) {
cout << "\nDone1.1";
Polygon custompts, customhull;
for (int r = 0; r < i_matrix.size(); r++) {
custompts.push_back(Point(i_matrix[r][0], i_matrix[r][1]));
}
computeConvexHull(custompts, customhull);
vector< vector<double> > res;
for (int i = 0; i < 3; i++)
{
vector<double> v1{ customhull[i].x, customhull[i].y };
res.push_back(v1);
}
return res;
}
int main()
{
// Create an empty vector
vector< vector<double> > mat, mat2;
vector<double> myRow1{0, 0};
mat.push_back(myRow1);
vector<double> myRow2{ 7.61, 9.48 };
mat.push_back(myRow2);
vector<double> myRow3{ 0, 9.48 };
mat.push_back(myRow3);
cout << "Done1";
mat2 = customComputeConvexHull(mat);
cout << "Done2";
return 0;
}
My header file "broker.h" is
#ifndef _BROKER_
#define _BROKER_
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <list>
#include <iterator>
#include <vector>
#include "strategy.h"
#include "utils.h"
using namespace std;
class Broker{
private:
vector< vector<double> > buy_signals; //time X codes
vector< vector<double> > sell_signals; //time X codes
vector< vector<double> > positions; //time X codes
vector< vector<double> > cashs; //time X 1
vector< vector<double> > prices; // time X codes
vector<double> position;
fstream fs;
fstream indi;
vector<string>codes;
vector<string>time_index;
int n_cols, n_rows;
double return_mean, sharp;
Strategy strategy;
public:
double cash;
double unit;
template<typename T>
void set_data(vector<string>& _codes, const map<string, vector<T>>>& _fs, const map<string, vector<T>>>& _indi, const vector<vector<double>>& _prices, const vector<string>& _time_index){
codes = _codes;
time_index = _time_index; //2015-2020
n_cols = codes.size();
n_rows = time_index.size();
/*
I don't know which data type is better for multi-index columns
fs=_fs;
indi = _indi;
*/
buy_signals = zero_vector(buy_signals, n_rows, n_cols);
sell_signals = zero_vector(sell_signals, n_rows, n_cols);
positions = zero_vector(positions, n_rows, n_cols);
cashs = zero_vector(cashs, n_rows, 1);
prices = _prices;
vector<vector<double>> temp;
position = zero_vector(temp, 1, n_cols)[0];
};
void update_data(Strategy s, int date_index){
cash = s.cash;
position = s.position;
cashs[i] = s.cash; // times X 1 : vector< vector<int> >
positions[i] = s.position; // times X codes : vector<vector<int>>
buy_signals[i] = s.buy_signal;
sell_signals[i] = s.sell_signal;
};
void run(){
for (int i=0; i < n_rows ; i++) {
string date = time_index[i];
string year = date.substr(0,4);
string prev_year = to_string(stoi(year)-1);
// 추상적 데이터 접근 - fs 데이터 타입 정해진 후 수정 바람
prev_fs_row = fs[prev_year]; // Not exact fs data type
curr_fs_row = fs[year];
curr_indi_row = indi[date];
Strategy strat = Strategy();
strat.set_data(prev_fs_row, curr_fs_row, curr_indi_row, codes, unit, cash);
strat.run();
update_data(strat, i);
}
};
void performance(){
vector<double> last_price = prices.back(); // {vector<int>, vector<int>, ....}
vector<double> total_remain_num = position;
vector<vector<double>> total_buy_data = d2_vec_mul(prices, buy_signals);
vector<vector<double>> total_sell_data = d2_vec_mul(prices, sell_signals);
double total_buy = sum_vector(sum_vector(total_buy_data, 1))[0][0];
double total_sell = sum_vector(sum_vector(total_sell_data, 1))[0][0];
double total_remain = vec_mul(last_price, total_remain_num)[0];
double profit = total_sell + total_remain - total_buy;
if (total_buy) {
return_mean = profit/total_buy;
}
else{
cout << "No buy!" <<endl;
return;
}
int n_rows = time_index.size();
// prices : already change from na -> 0 (from python)
vector<vector<double>> posses_stock_value = sum_vector(d2_vec_mul(positions, prices), 1); // times X 1
vector<vector<double>> accumulates = sum_vectors(cashs, posses_stock_value);
vector<vector<double>> shift_accumulates = shift_vector(accumulates);
vector<vector<double>> daily_return = divide_vectors(sum_vectors(accumulates, shift_accumulates, 0), shift_accumulates);
vector<double> temp ={1}; vector<vector<double>> ones(n_rows, temp);
daily_return = sum_vectors(daily_return, ones, 0);
temp.clear();
temp.push_back(return_mean); vector<vector<double>> daily_return_mean(n_rows, temp);
vector<vector<double>> daily_Err = (sum_vectors(pop_front(daily_return), pop_front(daily_return_mean));
double SSE = sum_vector(d2_vec_mul(daily_Err, daily_Err));
double std = power_vector(SSE, 0.5);
sharp = return_mean / std;
}
};
#endif
And there is an error in #ifndef BROKER as "There is #include error. Please update includePath."
My c_cpp_properties.json is
My project folder location is
However, my includepath is correct and when I just a simple HelloWorld.cpp there is no error. Why is there an error in #ifndef??
I am a novice at C++. I have started writing a rather large code on a project and I want to make a good base for that. I get the following error when running in Visual Studio:
Exception thrown: read access violation. this was nullptr. occurred
After searching similar questions, I could not find the solution for my code. The error is occurring in Driver.cpp at:
m_setup->SetEquation(...)
Any help is really appreciated. I also appreciate if you have suggestion to improve my code structure.
Main.h:
#ifndef FEM_AD1D_MAIN_H
#define FEM_AD1D_MAIN_H
namespace FEM_AD1D
{
class Driver;
Driver* m_driver;
}
#endif
Main.cpp:
#include "Main.h"
#include "Driver.h"
#include <iostream>
using namespace FEM_AD1D;
int main()
{
std::cout << "Hello World!\n";
m_driver->Run();
}
Driver.h:
#ifndef FEM_AD1D_DRIVER_H
#define FEM_AD1D_DRIVER_H
namespace FEM_AD1D
{
class Setup;
class Driver
{
public:
Driver(Setup* setup);
void Run();
void PreProc();
private:
Setup* m_setup;
const int m_nDim = 1;
const double m_aCoef = 1.0;
const double m_bCoef = 3.0;
const double m_cCoef = 0.0;
const double m_fCoef = 1.0;
const double m_xMin = 0.0;
const double m_xMax = 1.0;
const int m_nElem = 5;
const int m_elemType = 2;
const double m_meshStretch = 0.0;
const int m_nGaussPoint = 3;
};
}
#endif
Driver.cpp:
#include "Driver.h"
#include "Setup.h"
#include <iostream>
#include <array>
using namespace FEM_AD1D;
Driver::Driver(Setup* setup)
{
m_setup = setup;
//m_setup = new Setup();
}
void Driver::Run()
{
PreProc();
}
void Driver::PreProc()
{
std::cout << "Hello World 2!\n";
m_setup->SetEquation(m_nDim, m_aCoef, m_bCoef, m_cCoef, m_fCoef);
}
Setup.h:
#ifndef FEM_AD1D_SETUP_H
#define FEM_AD1D_SETUP_H
#include <vector>
namespace FEM_AD1D
{
class Setup
{
public:
Setup();
void SetEquation(int nDim, double aCoef, double bCoef, double cCoef, double fCoef);
private:
int m_nDim;
double m_aCoef;
double m_bCoef;
double m_cCoef;
double m_fCoef;
};
}
#endif
Setup.cpp:
#include "Setup.h"
#include "Driver.h"
#include <iostream>
#include <vector>
using namespace FEM_AD1D;
Setup::Setup() :
m_nDim(0),
m_aCoef(0.0),
m_bCoef(0.0),
m_cCoef(0.0),
m_fCoef(0.0)
{
}
void Setup::SetEquation(int nDim, double aCoef, double bCoef, double cCoef, double fCoef)
{
// Set the coefficients of the equation
std::cout << "Hello World 3!\n";
m_nDim = nDim;
m_aCoef = aCoef;
m_bCoef = bCoef;
m_cCoef = cCoef;
m_fCoef = fCoef;
}
I am trying to create multiple instances of a static c++ library I wrote, but I can't create multiple instances of it... When I create two instances and write different data to them, I read the same data from both of the instances. Here is my code:
.cpp file:
// MathFuncsLib.cpp
// compile with: cl /c /EHsc MathFuncsLib.cpp
// post-build command: lib MathFuncsLib.obj
/*
DECLARING VECTORS
|3,6,4|
|9,1,5|
|2,0,2|
|5,3,6|
Should be inputted as:
int a[] = {3,6,4,9,1,5,2,0,2,5,3,6} with x = 3 and y = 4
Inputting training vals:
|0.1 (inp1),0.1 (inp2) ,0.1 (targeted output)| depends on the number of inputs and outputs
|9,1,5|
|2,0,2|
|5,3,6|
*/
//#include "stdafx.h"
#include "vector.h"
#include "iostream"
#define DEBUG
#include <stdexcept>
//using namespace std;
double* vectorLib::arrayPtr;
int vectorLib::x;
int vectorLib::y;
vectorLib::vectorLib(int xInp, int yInp) {
vectorLib::arrayPtr = new double[xInp*yInp];
vectorLib::x = xInp;
vectorLib::y = yInp;
//return 0;
}
double vectorLib::sigmoid(double inp) {
return 1 / (1 + exp(-inp));
}
double* vectorLib::getArrayPtr() {
return vectorLib::arrayPtr;
}
double vectorLib::read(int xInp, int yInp) {
#ifdef DEBUG
if (xInp >= vectorLib::x) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_READ\n";
while (1);
}
if (yInp >= vectorLib::y) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_READ\n";
while (1);
}
#endif // DEBUG
return *(arrayPtr + xInp + vectorLib::x*yInp);
}
void vectorLib::write(int xInp, int yInp, double data) {
#ifdef DEBUG
if (xInp >= vectorLib::x) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_WRITE\n";
while (1);
}
if (yInp >= vectorLib::y) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_WRITE\n";
while (1);
}
#endif // DEBUG
vectorLib::arrayPtr[xInp + vectorLib::x*yInp] = data;
}
void vectorLib::writeArr(double* inpArr) {
int i;
for (i = 0; i < vectorLib::x*vectorLib::y; i++) {
vectorLib::arrayPtr[i] = *(inpArr + i);
}
}
void vectorLib::sigmoidVect() {
int yy;
int xx;
for (yy = 0; yy < vectorLib::y; yy++) {
for (xx = 0; xx < vectorLib::x; xx++) {
write(xx, yy, sigmoid(read(xx, yy)));
}
}
write(0, vectorLib::y - 1, 1);
}
int vectorLib::getX() {
return vectorLib::x;
}
int vectorLib::getY() {
return vectorLib::y;
}
int vectorLib::totalVectSize() {
return vectorLib::x * vectorLib::y;
}
void vectorLib::printVector() {
int yy;
int xx;
for (yy = 0; yy < y; yy++) {
for (xx = 0; xx < x; xx++) {
std::cout << vectorLib::read(xx, yy);
if (xx + 1 != x) {
std::cout << ",";
}
}
std::cout << "\n";
}
}
vectorLib* vectorLib::vectorMult(vectorLib* vect1, vectorLib* vect2) {
#ifdef DEBUG
if (vect1->getX() != vect2->getY()) {
std::cout << "INPUTS_DONT_MATCH_VECTORMULT\n";
while (1);
}
#endif // DEBUG
vectorLib toRet(vect1->getX(), vect2->getY());
int i;
for (i = 0; i < vect2->getX(); i++) {
int p;
for (p = 0; p < vect1->getY(); p++) {
double tempOut = 0;
int q;
for (q = 0; q < vect1->getX(); q++)
{
tempOut += vect1->read(q, p) * vect2->read(i, q);
}
toRet.write(i, p, tempOut);
}
}
return &toRet;
}
.h file:
//#include "stdafx.h"
using namespace std;
class vectorLib
{
//int x, y;
public:
static double* arrayPtr;
static int x;
static int y;
//Constructor takes x and y of the vector
vectorLib(int xInp, int yInp);
//The pointer to the array that holds all the doubles in the vector
static double* getArrayPtr();
//Read the vector at a specified x and y
static double read(int xInp, int yInp);
//Write one double to a specific location
static void write(int xInp, int yInp, double data);
//Write the array inside the vector class
static void writeArr(double* inpArr);
//Takes sigmoid of whole vector
static void sigmoidVect();
//Returns x of vector
static int getX();
//Returns y of vector
static int getY();
//Returns total size of vector
static int totalVectSize();
//Returns a vector pointer to the multiplication result
static vectorLib* vectorMult(vectorLib* vect1, vectorLib* vect2);
//Prints vector
static void printVector();
private:
static double sigmoid(double inp);
};
Main file:
#define DEBUG
#include "stdafx.h"
#include "vector.h"
#include "iostream"
using namespace std;
int main()
{
vectorLib testVectLol(1, 3);
vectorLib testVect(3, 4);
double vectInp[] = { 1,1,1,
1,1,1,
1,1,1,
1,1,1};
double vectInp2[] = { 0.5,0.5,0.5 };
testVect.writeArr(vectInp);
testVectLol.writeArr(vectInp2);
testVect.printVector();// Both print 0.5, 0.5, 0,5
testVectLol.printVector();// Both print 0.5, 0.5, 0,5
while (1);
return 0;
}
Thanks in advance! I've been struggling with this for hours. I would really appreciate any help!
Jasper
In my test program I have two points, and I want to find distance between them with my distancefrom. But I get answer 0.
Why does it give 0?
How can I fix it?
Point<2> v1;
// this should have {0.0, 0.0}
Point<2> v3 { list{2.0,3.0} };
float f = v1.distanceFrom(v3);
cout << f << endl;
I have a point.h file.
#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <list>
#include <sstream>
#include <string>
using std::stringstream;
#include <cmath>
using namespace std;
template<unsigned short n>
class Point {
public:
list <float> coords = {0.0};
Point <n>() = default;
Point <n>(list<float> coords){
if (coords.size()!=n) {
throw string ("Vale koordinaatide arv");
}
this-> coords=coords;
}
string toString(){
string sone;
ostringstream ss;
sone.append("(");
auto it3= coords.begin();
while ((it3) != coords.end()){
ss << (*it3);
sone.append(ss.str());
ss.str("");
sone.append(",");
++it3;
}
sone.pop_back();
sone.append(")");
return sone;
}
float distanceFrom (Point <n> v){
float s=0;
list<float> coords;
auto it1= coords.begin();
auto it2= v.coords.begin();
while ((it1) != coords.end()){
s+=(*it1 -*it2)*(*it1-*it2);
it1++;
it2++;
}
return sqrt(s);
}
friend std::ostream& operator <<(std::ostream& out, const Point<n>& v)
{
out << "("<<"Test"<<")";
return out;
}
};
#endif
First, your coords list does not know you want its size to be n. Its size after default initialization like the following is 1:
list <float> coords = {0.0};
The proper way to construct it would be:
list <float> coords = list <float> (n, 0.0);
Second, you allocate a new coords inside the function distanceFrom:
list<float> coords;
This shadows the real coords of the point which you in fact want to use. Remove that line, and you will be fine.
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
class pointDistance{
int x, y;
public:
pointDistance (int a, int b){
x =a;
y =b;
}
void pointShow(){
cout<<"The Point is ("<<x<<","<<y<<")"<<endl;
}
friend void Distance(pointDistance , pointDistance);
};
//formula of distance between two points:
//d =((x1^2 - x2^2) + (y1^2 - y2^2))^1/2
void Distance(pointDistance o1, pointDistance o2)
{
// pointDistance o3;
int d1,d2;
d1 = (o1.x -o2.x)*(o1.x -o2.x);
d2 = (o1.y - o2.y)*(o1.y - o2.y);
cout<<"So the distance between two point is "<< sqrt(d1+d2)<<endl;
}
int main(){
pointDistance one(4,5);
one.pointShow();
pointDistance two(0,6);
two.pointShow();
Distance(one, two);
return 0;
}