簡體   English   中英

c++ 指針使用向量 class

[英]c++ pointers using vector class

好吧,我正在學習使用向量 class 結合指針,我遇到了以下問題:

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
vector<vector<vector<float>>*> t;

t是指向浮點 2D 向量的指針向量。

因此*t[0][0][0] (這意味着取消引用最里面的向量,它不是指針)實際上應該是(*t[0])[0][0] ,這意味着取消引用最外面的向量.

t[0] 或vector<vector<float>>*是指向地址的指針(參見t[0] )。 因為它是一個指針,所以你使用 "->" t[0]->at(i)作為運算符來訪問諸如at()之類的方法,它返回索引的第 i 個元素。 因為還有一個不是指針的向量( vector<float> )。 在我們的例子中,你做點“。” 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;

好吧,如果向量 class 與指針相結合,我正在學習工作

嗯,聽起來已經很可疑了。 使用指針向量有很多不受歡迎的編碼模式。

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

是的,所以...不要寫那個。 我的意思是,我並沒有禁止你寫那個,但你想寫的不太可能。 為什么要分配和維護大量向量——你的“內部”向量? 以及大量的vector-of-vector,你的中級向量? 最后,為什么要跟蹤結構外部維度的分配——指向向量的向量的指針?

如果你想要一個floats的 3 維結構,要么寫一個 3D 張量 class,要么為你的張量的所有元素分配一個大數組,然后使用這個指南支持庫實現中的gsl::multispan來訪問你的數據作為3 維容器,並使用三元組索引:

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 的用途是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM