C++ weird problem, Undefined reference - c++

getting error: neljastest.cpp: undefined reference to Vector2::Vector2(float, float)
neljastest.cpp:
#include <cstdlib>
#include <iostream>
#include "../include/Vector2.h"
#include "../include/neljas.h"
using namespace std;
int main (int argc, char* argv[]) {
Vector2 p1 (1.0, 2.0);
Vector2 p2 (0.0, 0.0);
Vector2 p3 (5.0, 2.0);
return EXIT_SUCCESS;
}
vector2.h:
#ifndef VECTOR2_H
#define VECTOR2_H
#include <iostream>
using std::ostream;
class Vector2 {
public:
float x;
float y;
Vector2();
Vector2(float nx, float ny);
float distanceFrom(Vector2 v);
};
ostream& operator << (ostream& valja, Vector2 v);
#endif
vector2.cpp:
#include "../include/Vector2.h"
#include <cmath>
using namespace std;
Vector2::Vector2() {
x = 0;
y = 0;
}
Vector2::Vector2(float nx, float ny) {
x = nx;
y = ny;
}
float Vector2::distanceFrom(Vector2 v) {
return sqrt( (x - v.x)*(x - v.x) + (y - v.y)*(y - v.y) );
}
ostream& operator << (ostream& os, Vector2 v) {
return os << "(" << v.x << "," << v.y << ")";
}

C/C++ are case sensitive for headers too.
It seems that on vector2.cpp and neljastest.cpp you must change the include from:
#include "../include/Vector2.h"
To:
#include "../include/vector2.h"
I pasted all your sources on the same folder and successfully compiled them with:
g++ neljastest.cpp vector2.cpp -o neljastest
Edit:
Your problem is that the linking process of neljastest.cpp depends on src/vector2.cpp, and you are not doing that on the Makefile

Related

How to use ceres-solver to solve high dimensional non-linear problem?

     I need to solve the optimization problem: . A and b are known. I use Zero to represent A and b to facilate the expression in the following code. The error is caused by problem.AddResidualBlock(cost_function, nullptr, &X); because the third argument needs to be double type and X is a vector with 50 elements. Can you give me some advice?
#include <cmath>
#include <ceres/ceres.h>
#include <Eigen/Core>
#include <Eigen/Eigen>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/StdVector>
#define PhaseNums 25
using namespace std;
using namespace ceres;
using namespace Eigen;
struct GammaResidual
{
GammaResidual(const MatrixXf A, const VectorXf b) : A_(A), b_(b) {}
template <typename T>
bool operator()(const T* const x, T* residual) const {
residual[0] = (A_ * x[0] - b_).transpose() * (A_ * x[0] - b_);
return true;
}
private:
const MatrixXf A_;
const VectorXf b_;
};
int main()
{
MatrixXf A = MatrixXf::Zero(2 * PhaseNums, 2 * PhaseNums);
VectorXf b = VectorXf::Zero(2 * PhaseNums);
VectorXf X = VectorXf::Zero(2 * PhaseNums);
Problem problem;
CostFunction* cost_function = new AutoDiffCostFunction<GammaResidual, 1, 1>(
new GammaResidual(A, b));
problem.AddResidualBlock(cost_function, nullptr, &X);
ceres::Solver::Options options;
options.minimizer_progress_to_stdout = true;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
cout << summary.BriefReport() << endl;
}
I guess that If your X is a vector, you need to loop through it and add a residual a residual block for each x. Makes sense?

Create a sum of two Array instances

The essence of what I want to do is to take two instances of Vector2D and create a third vector that is to be returned and made into the third instance. The problem I am facing is that I am not entirely sure on how to go ahead in doing so. I have tried to find the syntax for sending in instances, if there is such a one, but I have not managed to find anything useful in any of my books.
#include<iostream>
#include<string>
#include<array>
using namespace std;
class vector2D
{
public:
array<float, 2> get()
{
return xy_coord;
}
void set(float x, float y)
{
xy_coord[0] = x;
xy_coord[1] = y;
}
array<float, 2> vectorAdd(a, b)
{
array<float, 2> c;
for (int i = 0; i < 2; i++)
{
c[i] = a[i] + b[i];
}
return c;
}
private:
array<float, 2> xy_coord;
};
int main()
{
string y;
vector2D a, b, c;
array<float, 2> temp;
a.set(2.0, 3.0);
b.set(4.0, 5.0);
temp = c.vectorAdd(a, b);
c.set(temp[0], temp[1]);
getline(cin, y);
}
The idea is to send in the instances a and b to vectorAdd and sum them up and then set c equal to the returned value (I am sure there is a better way to write the code in the main(), but I am not sure how). In short, what would a and b need to be defined as to make this work, assuming it can work at all.
Maybe you could do something like this instead, so you don't have to pass array around:
#include <iostream>
class Vector2D
{
private:
double _x;
double _y;
public:
Vector2D() = delete;
Vector2D(double x, double y) : _x(x), _y(y) {}
double X() const { return _x; }
double Y() const { return _y; }
Vector2D operator+(Vector2D const &v) const
{
return Vector2D(X() + v.X(), Y() + v.Y());
}
};
int main()
{
Vector2D v1(10.0, 20.0);
Vector2D v2(100.0, 200.0);
Vector2D v3 = v1 + v2;
std::cout << v3.X() << " " << v3.Y();
return 0;
}
Prints:
110 220
Do you need to use array<float, 2>? Have you thought of using pair<float, float>?
A lot (all?) of the operations that you have in your Vector2D class come for free with Pair<>.
Then you just create operator+ as others have suggested.
#include <iostream>
#include <utility>
using namespace std;
using Coord = pair<float, float>;
template <typename L, typename R>
Coord operator+(const L& x, const R& y) { return std::make_pair(x.first + y.first, x.second + y.second); }
int main()
{
Coord a { 5.0f, 6.0f };
Coord b { 7.0f, 9.0f };
Coord c = a + b;
std::cout.precision(5);
std::cout << "c= (" << std::fixed << c.first << ", " << c.second << ")" << std::endl;
return 0;
}

Generate All Possible Permutations of Vector of Objects

Given a vector of coordinates corresponding to city locations on a grid, how can I generate every permutation of these point objects? I suspect there is a problem with using a user-defined class (Point, in my case) with the predefined function next_permutation.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Point
{
public:
double x, y;
Point(int x, int y);
friend ostream& operator<< (ostream &out, const Point &p);
};
Point::Point(int xCoord, int yCoord)
{
x = xCoord;
y = yCoord;
}
ostream& operator<< (ostream &out, const Point &p)
{
out << "(" << p.x << ", " << p.y << ")";
return out;
}
int main()
{
vector<Point> points = { {3,5}, {10,1}, {2,6} };
do
{
for (Point pt : points)
{
cout << pt << " ";
}
cout << endl;
} while (next_permutation(points.begin(), points.end()));
}
A couple of things,
first to use next_permutations the container must be sorted.
second to compare two custom objects for sort and next_permutations, you need to overload the < operator.
something like this should work:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Coords
{
public:
int x = 0;
int y = 0;
//This uses a simple lexicographical ordering, modify to suit your needs.
bool operator <( const Coords& rhs )
{
if ( x == rhs.x )
{
return y < rhs.y;
}
else
{
return x < rhs.x;
}
}
};
vector<vector<Coords>> GetPermutaions( vector<Coords>& vec )
{
vector < vector<Coords>> outVal ;
//if you can guarantee vec will be sorted this can be omitted
sort( vec.begin() , vec.end() );
do
{
outVal.emplace_back( vec );
} while ( next_permutation( vec.begin() , vec.end() ) );
return outVal;
}
One thing to remember, this function will leave vec in a sorted state. If you need the original state, create a copy of vec to do the permutations.
Ex snippet:
#include<iostream>
#include<vector>
#include<algorithm>
int main()
{
typedef std::vector<int> V; //<or_any_class>
V v;
for(int i=1;i<=5;++i)
v.push_back(i*10);
do{
std::cout<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<" "<<v[4]<<std::endl;
}while(std::next_permutation(v.begin(),v.end()));
return 0;
}

Need help trying to insert numbers from the keyboard into a vector C++

I am writing a class that holds an RGB color. I have been trying a bunch of different things to try to insert the numbers from the keyboard, but nothing is working. I have four different operators overloaded because that's what I need to do for the assignment.
This is my main page.
#include <iostream>
#include "color.h"
#include <vector>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#include <istream>
using namespace std;
string printColor(Color c);
void printBox(vector<Color> box);
int main() {
vector<Color> box;
Color a;
cout << "Enter three ints.";
cin >> a;
box.push_back(a);
//box.push_back(b);
//box.push_back(Color(100,100,100));
//box.push_back(Color(10,10,125));
//box.push_back(Color(150,1,150));
printBox(box);
sort(box.begin(), box.end());
printBox(box);
printColor(a);
return 0;
}
void printBox(vector<Color> box) {
vector<Color>::iterator it; //iterators are pointers
cout << "------------------------------------------" << endl;
for (it = box.begin(); it != box.end(); it++) {
cout << *it << endl;
}
}
string printColor(Color c) {
char temp [8];
sprintf(temp,"#%02x%02x%02x",c.red, c.green, c.blue);
return string(temp);
}
Here is my Source file
#include "color.h"
using namespace std;
std::ostream & operator<<(std::ostream & out, const Color &b){
out<< "Red: " << b.red << " Green: " << b.green << " Blue: " << b.blue;
return out;
}
bool operator<(const Color &a, const Color &b){
return a.red < b.red && a.blue < b.blue && a.green < b.green;
}
bool operator==(const Color &a, const Color &b){
bool result;
result = a.red == b.red && a.blue == b.blue && a.green == b.green;
return result;
}
Here is my header file
#ifndef COLOR_H_
#define COLOR_H_
#include <iostream>
struct Color {
int red;
int green;
int blue;
Color(int _red, int _green, int _blue){
red = _red;
green = _green;
blue = _blue;
}
};
bool operator<(const Color &a, const Color &b);
bool operator==(const Color &a, const Color &b);
std::ostream & operator<<(std::ostream & out, const Color &b);
#endif /* COLOR_H_ */
You can use std::istream_iterator to fetch types from std::cin more intuitively. FYI, you can "close" std::cin in the command line by pressing CTRL+D.
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <tuple>
#include <vector>
class Color {
int R, G, B;
public:
Color() = default; // Required for iterator-support
Color(int r, int g, int b) : R{r}, G{g}, B{b} {};
friend std::istream& operator>>(std::istream&, Color&);
};
std::istream& operator>>(std::istream& in, Color& c)
{
std::array<int, 3> rgb{};
std::copy_n(std::istream_iterator<int>{in}, 3, rgb.begin());
std::tie(c.R, c.G, c.B) = std::tie(rgb[0], rgb[1], rgb[2]);
return in;
}
int main()
{
std::vector<Color> colors{
std::istream_iterator<Color>{std::cin}
, std::istream_iterator<Color>{}
};
std::cout << colors.size() << '\n';
}
Demo

Unrecoverable block scoping error, array of C++ functors

I'm trying to create an array of functors at compile time, like so: (complete file):
#include <functional>
using namespace std;
function< float( float tElevation, float pAzimuth )> colorFunctions[] = {
[]( float tElevation, float pAzimuth ) -> float {
return 2.0f ;
},
} ;
int main()
{
}
That works fine.
But as soon as you try to create a local inside the functor block, like this:
function< float( float tElevation, float pAzimuth )> colorFunctions[] = {
[]( float tElevation, float pAzimuth ) -> float {
float v = 2.0f ;
return v ;
},
} ;
You get Error 1 error C1506: unrecoverable block scoping error
How can I declare locals inside these blocks? It doesn't seem to work.
I can reproduce this on MSVC 2010, SP1. VS10 is known for some problems with lambdas and scoping. I've tried around a lot but found nothing beautiful. Ugly, ugly workaround that will have some initialization overhead but else work as intended:
#include <functional>
#include <boost/assign/list_of.hpp>
#include <vector>
using namespace std;
typedef function< float( float tElevation, float pAzimuth )> f3Func;
vector<f3Func const> const colorFunctions = boost::assign::list_of(
f3Func([]( float /*tElevation*/, float /*pAzimuth*/ ) -> float {
float v = 2.0f ;
return v ;
}))
([](float a, float b) -> float {
float someFloat = 3.14f;
return a*b*someFloat;
})
;
#include <iostream>
int main()
{
cout << colorFunctions[1](0.3f,0.4f) << '\n';
}
I compiled the following code on ubuntu 12.04 with the following line:
g++-4.7 -std=c++0x main.cpp
And it worked fine.
What platform and what compiler are you using?
#include <iostream>
#include <functional>
using namespace std;
function<float (float,float)> funcs[] = {
[] (float a, float b) -> float {
float c = 2.0f;
return c;
}
};
int main() {
std::cout << funcs[0](1,2) << std::endl;
}