Last active
November 19, 2020 20:55
-
-
Save gagolews/9206364 to your computer and use it in GitHub Desktop.
operator() for structs in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
// an illustration for my Julia-related question on julia-users | |
struct datfun { | |
// some data | |
vector<double> x; | |
vector<double> y; | |
// operator() lets the object act like a function; | |
// note that here we operate on the object's fields | |
// (one function, different "hidden" input data) | |
vector<double> operator()(int i) { | |
vector<double> ret(2); | |
ret[0] = x[i]; | |
ret[1] = y[i]; | |
return ret; | |
} | |
datfun(const vector<double>& _x, const vector<double>& _y) { // auxiliary | |
x = _x; y = _y; | |
} | |
}; | |
ostream& operator<<(ostream& out, const vector<double>& v) { // auxiliary | |
for (int i=0; i<v.size(); ++i) | |
out << v[i] << " "; | |
out << endl; | |
} | |
int main() { | |
// example vectors: | |
vector<double> x1(10), y1(10), x2(10), y2(10); | |
for (int i=0; i<10; ++i) { | |
x1[i] = i+1; | |
y1[i] = 10*(i+1); | |
x2[i] = -x1[i]; | |
y2[i] = -y1[i]; | |
} | |
// create two objects: | |
datfun f1(x1, y1); | |
datfun f2(x2, y2); | |
// and now: | |
cout << f1(1); // 2 20 | |
cout << f2(1); // -2 -20 | |
x1[1] = 1000; | |
cout << f1(1); // 2 20 (no change -> deep copy) | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment