user294664 user294664 - 4 days ago 5
C++ Question

Identifying a class object with its member integer Id in C++

Look at the three classes and its data members, given below.

node class

class node
{
int node_id;
double x,y,z;

}


element class

class element
{
int element_id;
node node1,node2,node3;
}


mesh class

class mesh
{
/* I know that instead of pointer object we've to use smart pointer
in the vector but don't know how to use it.Any help is
appreciated. */

std::vector<node*> nodes; // stores node objects.
std::vector<element*> elements; //store element objects;
}


So I can easily instantiate node objects and can be stored in nodes of std::vector data-type. But I need to precisely know which node objects are there in the element to instantiate an object of element. node objects are stored in the vector array. Identifying a node object like nodes[i] is error prone in my case (i.e nodes[i] is not the exact i-th node, where i is the node-id) . So I would like to identify an node object based on its id. Please give me suggestions.

I hope my question make sense. Since I'm a beginner in c++ any edit is also appreciated to make question understandable.

Answer

I am not sure weather this is exactly what your problem is but providing a simle getter for id and then checking it may do as it looks like :

 class node
 {
     int node_id;
     double x,y,z;
 public:
     int getId(){ return node_id;}
 }

as for smart pointer in mesh class you could use

 class mesh
 {
      std::vector<std::unique_ptr<node>> nodes; // stores node objects.
      std::vector<std::unique_ptr<element>> elements; //store element objects;
      void test()
      {
         for(const auto& n : nodes)
         {
            if(n->getId() == /*what you want*/)
            {
                 //emplace/push_back in elements
            }
      }
}

for e.g.

Comments