I'm new to C++. And thus also the idea of using pointers. I have some arrays that I want to queue. I understand that my code does not work as I'm using pointers. However I do not know how I should fix this? I need the elements from the queue to be a float* type for later use with BLAS.
#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;
float* k = new float[len];
k = initialize(k,len);
for(int t=0;t<len;t++){
k[t] = 1;
printVector(k, len);
q.push(k);
k[t] = 0;
}
// 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);
q.pop();
}
return 0;
}
Bonus question does these types of "pointer arrays" have a special name? float* k = new float[len];
std::vector<float>. If you have to pass C arrays to BLAS functions you could extract them usingstd::vector::data()(or&std::vector::operator[0]). The size (number of elements) (which is probably required as well) is available withstd::vector::size().kis just a pointer to the first element of the new array. It is indistinguishable from a pointer to any otherfloat, except in what you can/must do with it.std::queue<std::vector<float>>you could just as easily doq.front().data().q.push();). The other loop shoulddelete[]the popped pointer resp. (Otherwise you might get memory leaks.) As you did it, all queue entries share the same storage (and hence the side effects). => Assigning a pointer does not copy the pointed contents.