I'm trying to access an element within a vector of class objects but I don't get it right. I guess it's something wrong with the constructor/deconstructor and reference but even the other questions like C++ destructor issue with std::vector of class objects, c++ vector of class object pointers or C++ vector of objects vs. vector of pointers to objects. Hopefully someone can help me to fix my code snippet.
node.h
class Node {
public:
Node();
Node(int id, const std::string& name);
Node(const Node& orig);
virtual ~Node();
void cout(void);
int get_id(void);
private:
int _id;
std::string _name;
};
node.cpp
#include "node.h"
Node::Node() {
}
Node::Node(int id, const std::string& name) : _id(id), _name(name) {
this->cout();
}
Node::Node(const Node& orig) {
}
Node::~Node() {
}
void Node::cout(void) {
std::cout << "NODE " << _id << " \"" << _name << "\"" std::endl;
}
int Node::get_id(void) {
return _id;
}
communication.h
#include "node.h"
class Com {
public:
std::vector<Node> nodes;
Com();
com(const Com& orig);
virtual ~Com();
void cout_nodes(void);
private:
};
communication.cpp
#include "communication.h"
Com::Com() {
nodes.push_back(Node(169, "Node #1"));
nodes.push_back(Node(170, "Node #2"));
}
Com::Com(const Com& orig) {
}
Com::~Com() {
}
void Com::cout_nodes(void) {
for (uint8_t i = 0; i < nodes.size(); i++) {
nodes[i].cout();
}
}
If I run Com com;
I get the expected output of:
[I 171218 13:10:10 Cpp:22] < NODE 169 "Node #1"
[I 171218 13:10:10 Cpp:22] < NODE 170 "Node #2"
but running com.cout_nodes();
results in:
[I 171218 13:10:14 Cpp:22] < NODE 0 ""
[I 171218 13:10:14 Cpp:22] < NODE 0 ""
As in C++ vector of objects vs. vector of pointers to objects everything works fine when I use references but I couldn't get std::iterator
and find_if
working than.
update: working find_if
statement and index calculation
auto iterator = std::find_if(nodes.begin(), nodes.end(), [&](Node node) {
return node.get_id() == 169;
});
if (iterator != nodes.end()) {
size_t index = std::distance(nodes.begin(), iterator );
std::cout << "Index of ID #169: " << index << std::endl;
}