gpt4 book ai didi

c++ - 队列数组指针 (C++)

转载 作者:行者123 更新时间:2023-11-28 01:32:46 24 4
gpt4 key购买 nike

我是 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];

最佳答案

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

稍微重新排序您的语句,我运行了 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;
}

输出是相同的。

Live Demo on coliru

关于c++ - 队列数组指针 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com