Finding a on object in a vector by one of its values - class

The problem I encountered and am unable to solve goes something like this. I have two classes:
class1
{
private:
int identifier;
double value;
public:
setters,getters,etc...
}
class2
{
private:
vector<class1> objects;
vector<int> some_value;
vector<double> other_value;
...
}
The problem is I need to search through the vector of objects in an object of the second class by its identifier in the class1 object(from a member function of class2). I tried something like:
int getObj(const int &ident, double &returnedValue, double &returnedOther_value)
{
int p;
p = find(objects.begin()->getIdentifier(),objects.end()->getIdentifier(),ident);
..
.. and then i was hoping to find a way to return from the found iterator values of corresponding(non-const) member variables value and other_value from both classes, but the code so far does not compile, because I'm likely doing the search all wrong. Is there a way I could do this with the find(or any other algorithm) or should I stick to my previous working realization with no algorithms?

You need to use find_if with a custom predicate. Something like:
class HasIdentifier:public unary_function<class1, bool>
{
public:
HasIdentifier(int id) : m_id(id) { }
bool operator()(const class1& c)const
{
return (c.getIdentifier() == m_id);
}
private:
int m_id;
};
// Then, to find it:
vector<class1>::iterator itElem = find_if(objects.begin(), objects.end(), HasIdentifier(ident));
I haven't tested it, so maybe it needs some tweaking.
If you have C11, I guess you can use lambdas, but I don't have it, so I haven't had the chance to learn them.
UPDATE:
I've added an example in http://ideone.com/D1DWU

Related

ClaiR/Rascal: Best way to list public functions?

I am parsing an C++ header file using ClaiR and want to get a list of the public functions.
visit(ast) {
case \class(_, name(n), _, decs): {
println("class name: <n>");
isPublic = true;
for (dec <- decs) {
switch(dec) {
case \visibilityLabel(\public()): {
println("Public functions");
isPublic = true;
}
case \visibilityLabel(\protected()): {
println("Protected functions");
isPublic = false;
}
case \visibilityLabel(\private()): {
println("Private functions");
isPublic = false;
}
case \simpleDeclaration(_, [\functionDeclarator([*_], [*_], name(na), [*_], [*_])]): {
if (isPublic) {
println("public function: <na>");
}
}
}
}
}
}
The above code works. But is there a better (smaller) way of acquiring the public functions?
In C++, the public/protected/private access modifiers aren't proper "modifiers" on declarations; instead, all member declarations following an access modifier (up to a possible next access modifier) have the declared visiblity (in your example, the second public: also makes myFunc4 public). It would be straightforward to implement an AST traversal to obtain members' visiblity information and add it to a new M3 table, though. Your suggestion of public void myFunc5(); is invalid syntax.
The ProblemType in the decl indicates that the first argument of the myFunc method is unresolved (likely due to a missing import). The toString of this ProblemType in the type information should not be there, though, that is a bug.
There's an M3 modifiers relation which might have the info you're looking for:
https://github.com/usethesource/rascal/blob/1514b30341525fe66cf99a64ed995052293f09d5/src/org/rascalmpl/library/analysis/m3/Core.rsc#L61
that relation can be composed with the o operator with the qualified names of your methods to see which modifiers are declared on which method
However, that relation must be extracted of course. Perhaps that still needs to be added to ClaiR?
I have some code the looks like this:
MyClass {
public:
void myFunc1();
private:
void myFunc2();
public:
void myFunc3();
void myFunc4();
m3.modifiers does not provide public/private information. I guess (have not tried), it will work for public void myFunc5();
I also see some strange errors.
<|cpp+method:///MyClass/myFunc(org.eclipse.cdt.internal.core.dom.parser.ProblemType#38270bb,unsigned.int,unsigned.int)|,virtual()>,
Is this for a type it cannot resolve (include not provided to parser)?

Shall I build a destructor in this classes?

I am currently working on building an ABM model using C++.
I have classes that have the need to interact with each other, because e.g. class B needs to examine values in class A and return some evaluation on it, which then class C might want to read. Classes need not to change other classes values, only to read from them.
Class B in my current implementation has a po
inter to a vector containing all members of Class A. The pointer is there for two order of reason: it makes easier to initialize the vector, and the vector is left in the scope of main so that I can access and loop over it, calling the members of class A for each agent.
My MCVE:
#include <iostream>
#include <vector>
using namespace std;
class A; // Forward declaration
class B{
int id,
some_value;
vector<A> * A_vec;
public:
// Overloaded constructor
B(int ID, vector<A> & PTR)
{
A_vec = & PTR;
id = ID;
some_value = 0;
};
// Copy Constructor
B( const B& that ):
id(that.id),
some_value(that.some_value)
{
// Pointer ??
};
// Non-default destructor -> uncomment leads to seg_fault
/*
~B(){ delete [] A_vec;};
*/
// Assignment operator
B& operator=(const B& that)
{
id = that.id;
some_value = that.some_value;
// Pointer ??
return *this;
};
//Methods to update different variables go here ..
void do_stuff();
};
class A{
B & class2_ref;
vector<double> o;
public:
int stuff;
// Overloaded constructor
A(int STUFF, B & REF, vector<double> O):
class2_ref(REF),
o(O)
{
stuff = STUFF;
};
// Methods to update different variables go here ..
};
void B::do_stuff()
{
int L = A_vec->size();
for(int l = 0; l<L; l++) some_value += (*A_vec)[l].stuff; // Perform some operation
};
int main(){
int I = 5; // Number of objects of A
vector<double> O(12,2); // Some numbers in here
B b(0,A_vec);
for(int i = 0; i< I; i++)
{
A a(i,b,O);
A_vec.push_back(a);
}
b.do_stuff();
cout<< "Debugging MCVE" << endl;
return 0;
}
My question then is:
Should I implement the destructor/copy constructor/assignment operator in class B? What about class A ? If so, can you please point me to the correct syntax(for the destructor the one above in comments leads to seg fault).
My understanding is that this might be one of the case in which I am happy with a "shallow" destruction of the pointer, because both class B and vector<A> will go out of scope at the return statement. class B owns the pointer, which gets destructed when it is due, and the same for vector.
But then, what about the other member from the rule of three?
There is only one object of class B planned, but I might (small chance) want to generalize later on.
if a class have a pointer type, you should implement a destructor, and i would suggest implementing a copy and an assignment operator as well, else you will be dealing with the same object from 2 different places, which could cause you some errors, for example -
void someFunction(B &b)
{
B a = b;
}
B b(0,A_vec);
someFunction(b); //After finishing someFunction, it will try to delete the vector from a , but it is the same vector you used in b.
b.do_stuff(); // Would cause a seg error
And for the destructor syntax, just delete the vector, not its content, it will use the vector default destrctor on the content:
delete A_vec
just make sure you dont use it if its not initialized, i would suggest just building a empty vector on each ctor of the class, that way you wont get a seg fault and you can use delete.

binding to constant values in mvvm

i have constant values (certain limits) i work with in the viewmodel but i need it in my view as well. what is the best way to do that?
constant:
private const int maxLevel = 4;
do i really need to make a property for each constant and bind to it like that:
private const int _maxLevel = 4;
public int MaxLevel
{
get { return _maxLevel; }
set
{
RaisePropertyChanged("MaxLevel");
}
}
maybe i could store all those values in a *.resx file like i do it with strings? what is the best practice here?
You can do:
namespace Foo.ViewModels
{
public class MainWindowViewModel{
public const int MaxLevel = 4;
...
}
}
and use it in the view:
<Label Content="{x:Static Foo.ViewModels:MainWindowViewModel.MaxLevel}"></Label>
Or generally speaking, bind to:
"{x:Static MyNameSpace:MyClass.MY_CONSTANT}"
Lose the setter. Property change notification is only needed to inform binding elements that the value has changed. Since MaxLevel is a constant its value never changes, thus you don't need it. You can't bind directly to a constant because in practice the compiler embeds the value into the code that accesses it at compile time, so for constant properties that are unlikely to need future modification I usually just do something like this:
public int MaxLevel { get {return 4;} }

Class in parameter of function (Arduino) does not compile

I am trying to create a simple class in C++, but I keep getting the compilation errors:
main:2: error: variable or field 'doSomething' declared void
main:2: error: 'person' was not declared in this scope
main:
class person {
public:
int a;
};
void doSomething(person joe) {
return;
}
main() and stuff would go here, but even if I include main(){}, the errors still occur. I also tried adding 2 closed parentheses after joe, but then that creates the error:
main: In function 'void doSomething(person (*)())':
main:8: error: request for member 'a' in 'joe', which is of non-class type 'person (*)()'
Any help is greatly appreciated. (I hope this isn't something really stupid I'm missing, because I've been researching for hours).
Edit: I found out this is an Arduino-specific error. This post answers it.
I found out after reading this post that a way to work around this is:
typedef struct person{
public:
int a;
};
void doSomething(void *ptr)
{
person *x;
joe = (person *)ptr;
joe->a = 3; //To set a to 3
//Everything else is normal, except changing any value of person uses "->" rather than "."
return;
}
main()
{
person larry;
doSomething(&larry);
}
So essentially it is:
-Change class to typedef struct
-in the parameter, replace newtype with void *something
-add person *x; and x = (person *)ptr; to the beginning of the function
-whenever accessing type property, use -> rather than .
I'm not a expert but when I try to do what you want to do, I do it this way:
//create an instance of my class
MyAwesomeClass myObject;
void myFunction(MyAwesomeClass& object){
//do what you want here using "object"
object.doSomething();
object.doSomethingElse();
}
void setup() {
//setup stuff here
myObject.init();
}
void loop() {
//call myFunction this way
myFunction(myObject);
}
As I said, I'm not a C++ expert but it does the job.
Hope it helps!
My guess is, you have an invalid syntax error somewhere in the declarations above "class person...". Can you copy and paste the whole file?

Unity3D. How to construct components programmatically

I'm new to unity and am having a bit of trouble getting my head around the architecture.
Lets say I have a C# script component called 'component A'.
I'd like component A to have an array of 100 other components of type 'component B'.
How do I construct the 'component B's programmatically with certain values?
Note that 'component B' is derived from 'MonoBehaviour' as it needs to be able to call 'StartCoroutine'
I'm aware that in unity you do not use constructors as you normally would in OO.
Note that 'component B' is derived from 'MonoBehaviour' as it needs to
be able to call 'StartCoroutine'
I'm aware that in unity you do not use constructors as you normally
would in OO.
That's true. A possibility is to istantiate components at runtime and provide a method to initialize them ( if initialization requires arguments, otherwise all initialization can be done inside Start or Awake methods ).
How do I construct the 'component B's programmatically with certain
values?
Here's a possible way:
public class BComponent : MonoBehavior
{
int id;
public void Init(int i)
{
id = i;
}
}
}
public class AComponent : MonoBehavior
{
private BComponent[] bs;
void Start()
{
bs = new BComponent[100];
for (int i=0; i < 100; ++i )
{
bs[i] = gameObject.AddComponent<BComponent>().Init(i);
}
}
}
Note that in the example above all components will be attached to the same GameObject, this might be not what you want. Eventually try to give more details.