mercredi 1 février 2023

Are Reference iterators faster than Normal iterators in C++? [closed]

Recently I was solving a question on leetcode using for-each loop (or range-based for loop). Initially, I have used a normal iterator as follows:

for(Node* node: tree){
    vec.push_back(node->val);
}

But then I changed the reference iterator as follows:

for(Node* &node: tree){
    vec.push_back(node->val);
}

Doing so there was a significant change in the runtime of the program. I am curious whether reference iterators are faster and/or space efficient than normal iterators or if they are similar.

EDIT:
As my question was closed I want to add more clarity. I was solving a question of level-order traversal of N-ary tree. Since level order traversal of a question requires breadth-first-search, I was using a queue to solve this problem. In my code there is a for loop that stores the children of a node in a temporary vector which is as follows:

for(Node* &node: curr->children){
   temp.push_back(node->val);
   q.push(node);
}

This is where I have used a range-based for loop (to iterate through children of a node).
However, I have a general query about whether or not there is any difference in terms of runtime and space between both of these iterators (normal and referenced one).

Aucun commentaire:

Enregistrer un commentaire