Reputation: 1260
I wrote a class in Java called Nod.java.
import java.util.ArrayList;
import java.util.Arrays;
class Nod {
int[] vol;
String op="";
Nod parent;
int adancime;
Nod (int[] vol, String op,Nod parent,int adancime){
this.vol=vol;
this.op=op;
this.parent = parent;
this.adancime=adancime;
}
public String toString() {
return op;
}
public int getAdancime() {
return adancime;
}
public ArrayList<Nod> getCale(ArrayList<Nod> lnoduri) {
lnoduri.add(0, this);
if (parent != null) lnoduri = parent.getCale(lnoduri);
return lnoduri;
}
public ArrayList<Nod> getCale()
{ return(getCale(new ArrayList<Nod>())); }
}
and I want to rewrite it in C++ but I don't know how to rewrite these two functions in C++:
public ArrayList<Nod> getPath(ArrayList<Nod> lnoduri) {
lnoduri.add(0, this);
if (parent != null) lnoduri = parent.getPath(lnoduri);
return lnoduri;
}
public ArrayList<Nod> getPath(){
return(getPath(new ArrayList<Nod>()));
}
These functions store the path of each nod to the parent.
Can you help me please?
EDIT
Because it is a related question, I add it here.
I wrote a function to "Vase" class in Java:
public ArrayList<Nod> succesori(Nod parent) {
// "Nod" is another class.
ArrayList<Nod> listTest = new ArrayList<Nod>();
// operations/conditions;
listTest.add(new Nod(vol,op,parent,adancime+1));
return(listTest);
}
and I want to rewrite in C++:
vector<Nod*> Vase::succesori(Nod *parinte)
{
vector<Nod*> *listTest = new vector<Nod*>();
// operations/conditions;
listTest.insert(new Nod(vol,op,parent,adancime+1));
return (*listTest);
}
But I get an error when I try to execut this command: listTest.insert(new Nod(vol,op,parent,adancime+1));
IntelliSense: expression must have class type
Error 1 error C2228: left of '.insert' must have class/struct/union
How can I add/insert in listTest a new Nod class?
Upvotes: 1
Views: 266
Reputation: 111259
You can write a direct translation into C++, but if you do this the program will probably be difficult to maintain and slow. Just remember that all methods are virtual by default, objects are passed by pointer, and vector
substitutes ArrayList
:
virtual vector<nod*> *getCale(vector<nod*> *lnoduri) {
lnoduri->insert(lnoduri->begin(), this);
if (parent != nullptr) lnoduri = parent->getCale(lnoduri);
return lnoduri;
}
virtual vector<nod*> *getCale() {
return getCale(new vector<nod*>());
}
Upvotes: 1
Reputation: 50044
The Java code looks a bit strange. If you really want to use recursion, then I recommend rewriting the methods as follows.
public void getCale(ArrayList<Nod> lnoduri) {
if (parent != null) {
parent.getCale(lnoduri);
}
lnoduri.add(this);
}
public ArrayList<Nod> getCale() {
ArrayList<Nod> result = new ArrayList();
getCale(result);
return result;
}
In C++, I would use only one member function.
std::vector<Nod*> getCale()
{
std::vector<Nod*> result;
for (Nod* n = this; n; n = n->_parent) {
result.push_back(n);
}
std::reverse(result.begin(), result.end());
return result;
}
Upvotes: 3