Reputation: 143
In c++ I pass a vector of 'Node' objects by reference to a function—addUnique—which either increments the 'count' property of an element in the vector or appends to the vector.
const char inputString[] = "aaccgtgacac";
int main(int argc, const char * argv[]) {
std::vector <Node> nodes;
for (char input: inputString) {
addUnique(nodes, input);
}
for (Node node: nodes) {
node.display();
}
}
void addUnique(std::vector<Node>& list, char check) {
for (Node used: list) {
if (used.baseChar == check) {
used.count++;
return;
}
}
Node node(check, 1);
list.push_back(node);
}
class Node {
public:
char baseChar;
Node* composition1;
Node* composition2;
unsigned int count;
Node(char newChar, unsigned int newCount) {
baseChar = newChar;
count = newCount;
}
void display();
};
The main function then outputs the returned cont values with their corresponding charValues:
Upvotes: 0
Views: 902
Reputation: 12928
Your loop where you increment the count, is iterating the Node
s by value:
for (Node used: list) { ... }
This makes a copy of each node, then you modify the copy and throw it away. Instead, make the loop use references:
for (Node& used: list) { ... }
Now you will modify the values in the vector, instead of the copy.
Upvotes: 1