Важное сообщение: хранение указателя (на массив или что-либо еще) не копирует содержимое.Он просто копирует его адрес.
Немного переупорядочив ваши операторы, я запустил образец OP (и выполняю то, что, вероятно, намеревался):
#include <iostream>
#include <queue>
using namespace std;
float* initialize(float* vec, int len){
for(int i = 0; i < len; ++i){
vec[i] = 0; // Initialize
}
return vec;
}
void printVector(float* vec, int len){
for(int i=0;i<len;i++)
cout << vec[i] << endl;
cout << "--" << endl;
}
int main ()
{
queue<float*> q;
int len = 3;
for(int t=0;t<len;t++){
float* k = new float[len];
k = initialize(k,len);
k[t] = 1;
printVector(k, len);
q.push(k);
}
// I would like the one below to give same output as above
cout << "Should have been the same:" << endl;
while (!q.empty()){
printVector(q.front(), len);
delete[] q.front();
q.pop();
}
return 0;
}
Вывод:
1
0
0
--
0
1
0
--
0
0
1
--
Should have been the same:
1
0
0
--
0
1
0
--
0
0
1
--
Использование new
в C ++ подвержено ошибкам и может быть предотвращено во многих случаях.Если сделать то же самое с std::vector<float>
, это может выглядеть так:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
void printVector(const float* vec, int len){
for(int i=0;i<len;i++)
cout << vec[i] << endl;
cout << "--" << endl;
}
int main ()
{
queue<std::vector<float> > q;
int len = 3;
for(int t=0;t<len;t++){
q.push(std::vector<float>(3, 0.0f));
q.back()[t] = 1.0f;
printVector(q.back().data(), q.back().size());
}
// I would like the one below to give same output as above
cout << "Should have been the same:" << endl;
while (!q.empty()){
printVector(q.front().data(), q.front().size());
q.pop();
}
return 0;
}
Вывод идентичен.
Демонстрация в реальном времени на coliru