c++中用vector創建多維數組的初始化方法


最近調試一個程序,在使用vector聲明一個二維數組時出現錯誤。錯誤的方法如下所示:

std::vector<std::vector<double> > sphereGrid;
int gridLA = angleSpanLA / angelAccuracy;
int gridLO = angleSpanLO / angelAccuracy;
sphereGrid = std::vector<std::vector<double> >( gridLA , gridLO );

會出現如下報錯:

/home/zn/VanishingPointDetection/src/VPDetection.cpp: In member function ‘void VPDetection::getSphereGrids(std::vector<std::vector<double> >&)’:
/home/zn/VanishingPointDetection/src/VPDetection.cpp:156:66: error: no matching function for call to ‘std::vector<std::vector<double> >::vector(int&, int&)’
  sphereGrid = std::vector<std::vector<double> >( gridLA , gridLO );

這就是因為二維數組的初始化出現了錯誤,一般的話要通過下面這種方式初始化

定義空二維vector,再賦值
vector<vector <int> > ivec(m ,vector<int>(n)); //m*n的二維vector,注意兩個 "> "之間要有空格!

所以我們要把程序改為

std::vector<std::vector<double> > sphereGrid;
int gridLA = angleSpanLA / angelAccuracy;
int gridLO = angleSpanLO / angelAccuracy;
sphereGrid = std::vector<std::vector<double> >( gridLA , std::vector<double>(gridLO)  );

就可以解決錯誤,通過這次改錯更加認識到了c++之vector的用法。

參考:https://blog.csdn.net/ldkcumt/article/details/51396980

https://blog.csdn.net/oNever_say_love/article/details/50763238


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM