最近調試一個程序,在使用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