C++中 使用數組作為map容器VAlue值的解決方法


1)是用Vector容器代替數組

2)使用數組指針(需要注意局部變量的問題,指針是否需要用new創建)

int red [ 3 ]   = { 1 , 0 , 0 }; 
int green [ 3 ] = { 0 , 1 , 0 }; 
int blue [ 3 ]     = { 0 , 0 , 1 }; 
std :: map < int , int (*)[ 3 ]> colours ; 
colours . insert ( std :: pair < int , int (*)[ 3 ]>(( GLUT_LEFT_BUTTON ,& red )); 
colours . insert ( std :: pair < int , int (*)[ 3 ]>(( GLUT_MIDDLE_BUTTON ,& blue )); 
colours . insert ( std :: pair < int , int (*)[ 3 ]>(( GLUT_RIGHT_BUTTON ,& green )); 
//Watch out for scope here, you may need to create the arrays on the heap.

3)使用結構體來構造代替數組的元素,或把數組直接放在結構體內

struct Triple 

    int color [ 3 ]; 
}; 

  //Later in code 
Tripple red = { 1 , 0 , 0 }, green = { 0 , 1 , 0 }, blue = { 0 , 0 , 1 }; 
std :: map < int , Triple > colours ; 
colours . insert ( std :: pair < int , Triple >(( GLUT_LEFT_BUTTON , red )); 
colours . insert ( std :: pair < int , Triple >(( GLUT_MIDDLE_BUTTON , blue )); 
colours . insert ( std :: pair < int , Triple >(( GLUT_RIGHT_BUTTON , green ));


免責聲明!

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



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