[Solved] Size of queue is reset to 0 in for statement c++


in

for (int i = 0; i <= vector_data.size(); i++) {
                    Instr = vector_date.front();
                    vector_data.pop();
                    hpp_DE.push(Instr); 
 }

the size of vector_data changes because of the pop and at the same time you increment i to compare it to the (modified) size, this is wrong if you want to copy all the elements.

You use struct as a type, strange

vector_date must be vector_data

With that :

int main()
{
  queue <int> hpp_DE;
  queue <int> vector_data;  

  vector_data.push(1);
  vector_data.push(2);

  for (int i = 0; i <= vector_data.size(); i++) {
    int v = vector_data.front();
    vector_data.pop();
    hpp_DE.push(v); 
  }

  cout << hpp_DE.size() << ':';

  while (!hpp_DE.empty()) {
    cout << ' ' << hpp_DE.front();
    hpp_DE.pop();
  }
  cout <<endl;
}

Compilation and execution :

/tmp % g++ -pedantic -Wextra v.cc
v.cc: In function 'int main()':
v.cc:13: warning: comparison between signed and unsigned integer expressions
/tmp % ./a.out
2: 1 2

(Use size_t rather than int for the index to remove the warning)

But with

#include <queue>
#include <iostream>
using namespace std;

int main()
{
  queue <int> hpp_DE;
  queue <int> vector_data;  

  vector_data.push(1);
  vector_data.push(2);
  vector_data.push(3);
  vector_data.push(4);
  vector_data.push(5);

  for (int i = 0; i <= vector_data.size(); i++) {
    int v = vector_data.front();
    vector_data.pop();
    hpp_DE.push(v); 
  }

  cout << hpp_DE.size() << ':';

  while (!hpp_DE.empty()) {
    cout << ' ' << hpp_DE.front();
    hpp_DE.pop();
   }
   cout <<endl;
}

that prints 3: 1 2 3

If the goal it to copy all just loop while vector_data is not empty to do the copy, or just assign one into the other ?

3

solved Size of queue is reset to 0 in for statement c++