[英]Eigen::Matrix<double,1,3> return type function in a struct type function
[英]Return type of double **function()
我希望編寫一個返回2D數組或矩陣的函數。 這是我的嘗試:
double **function(){
double d[2][2] = { { 1.1, 1.2 }, { 2.1, 2.2 } };
return d; //Error: return type does not match the function type.
}
int main(){
double d[2][2] = function(); //Error: initialization with '{...}' expected for aggregate object.
return 0;
}
而且我有錯誤。
誰能告訴我正確的方法或建議另一種方法。
先感謝您。
數組和指針有很大的不同。 是的, 做數組轉換為指針,以在第一機會的元素類型,但這並不意味着它們是相同的。
您嘗試轉換的實體在內存中的布局完全不同:
double
的兩個數組組成,兩個double
在內存中是連續的。 double
是指針的數組double
。 盡管兩者都可以以相當類似的使用體驗形式使用,但它們在程序中的處理方式完全不同。
但是,您可以執行此操作(假設您使用C ++ 11或更高版本的編譯器進行編譯):
#include <array>
std::array<std::array<double, 2>, 2> function() {
std::array<std::array<double, 2>, 2> d = { { { 1.1, 1.2 } , { 2.1, 2.2 } } };
return d;
}
int main(){
std::array<std::array<double, 2>, 2> d = function();
return 0;
}
將double **
替換為多維std::vector
或std::array
( std::array<std::array<double, 2>, 2>
)。 然后,您的函數可以按值返回多維數組。 例如:
std::array<std::array<double,2>, 2> function() {
std::array<std::array<double,2>, 2> d = { { { 1.1, 1.2 }, { 2.1, 2.2 } } };
// Check http://stackoverflow.com/questions/17759757/multidimensional-stdarray on the syntax to initialize this.
return d;
}
int main(){
std::array<std::array<double,2>, 2> d = function();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.