队列数组指针(C ++)

时间:2018-06-11 13:59:06

标签: c++ arrays pointers queue

我是C ++的新手。因此也是使用指针的想法。 我有一些我想排队的数组。我知道我的代码不起作用,因为我正在使用指针。但是我不知道应该怎么解决这个问题呢? 我需要队列中的元素是一个float *类型,以便以后与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;
}

奖金问题这些类型的“指针数组”是否有特殊名称? float * k = new float [len];

1 个答案:

答案 0 :(得分:2)

基本信息是:存储指针(指向数组或其他任何内容)不会复制内容。它只是复制它的地址。

重新命令你的语句我运行了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
--

在C ++中使用new容易出错,在很多情况下都可以防止。对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;
}

输出相同。

Live Demo on coliru