提问者:小点点

使用vector类的C++指针


好吧,我正在学习使用结合指针的向量类,我遇到了以下问题:

vector<vector<vector<float>>*> t;
vector<vector<float>> p = { { 6.2,7,8 } };
vector<vector<float>> g = { { 6.6,5.8,9 } };
t.push_back(&p);
t.push_back(&g)
cout << "Print address: " << t[0] << endl; // works well, I see the address
cout << "Print address: " << t[1] << endl; // works  well, I see the address

//However, when I tried to access the content I didn't:

cout << "Print content: " << *t[0][0][0] << endl;

//My expectation is see 6.2

共3个答案

匿名用户

vector<vector<vector<float>>*> t;

T是指向Float的2D向量的指针向量。

因此*t[0][0][0](这意味着取消引用内部most向量,它不是指针)实际上应该是(*t[0])[0][0],这意味着取消引用外部most向量。

匿名用户

T[0]或Vector>*是指向地址的指针(请参阅T[0])。 因为它是您使用的指针“->;” t[0]->at(i)作为运算符访问诸如at()这样的方法,它返回索引的第i个元素。 因为还有一个矢量(vector)不是指针。 在我们的情况下,你做点“。 T[0]->at().at()

vector<vector<vector<float>>*> t;
vector<vector<float>> p = { { 6.2, 7, 8 } };
vector<vector<float>> g = { { 6.6, 5.8, 9 } };
   
t.push_back(&p);
t.push_back(&g);
    
cout << "t[0] el addr -> " << t[0] << endl; 
cout << "t[1] el addr -> " << t[1] << endl; 

cout << "Content t[0]->[0].[0] => " << t[0]->at(0).at(0) << endl;

匿名用户

好吧,我正在学习如何将向量类与指针相结合

嗯,听起来已经很可疑了。 使用指针向量的编码模式有很多不希望的。

矢量>*> t;

是啊,所以。。。 别这么写。 我的意思是,我不是禁止你写那个,但这是你想要写的极不可能。 为什么要分配和维护大量的向量--你的“内部”向量? 以及大量的向量中的向量,你的中级向量? 最后,为什么要跟踪结构外部维度的分配--指向向量的向量的指针?

如果您想要floats的三维结构,要么编写一个3D张量类,要么为张量的所有元素分配一个大数组,然后使用本指南支持库实现中的GSL::MultiSpan将数据作为三维容器访问,并使用三元索引:

float data[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
multi_span<int, 2, 3, 2> span{data, 12};
std::cout << span[1][1][1] << '\n'; // Should output 8

另请参阅:gsl::multi_span用于什么?

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(vector|类|c++|指针)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?