C++ vector資料型別的用法
阿新 • • 發佈:2019-01-23
開發的時候一旦要用到一串自定義類或者一串結構體,並且要對這一串資料進行插入、索引、提取等操作的時候,我就會想到vector,雖然有時候會有種殺雞用牛刀的感覺,但是大多數情況下能把問題解決就好了,至於效率啊、冗餘啊、最優啊,就先放一邊吧,畢竟先解決有無的問題,再解決好壞的問題!
最近在研究影象中提取直線的演算法,就用到了儲存一系列線的結構的問題,不出意外,還是走向了vector。先看線的結構體的定義。
/*** Straight line segment.
*/
typedef struct Line {
/** Coordinates of endpoints. */
double
/** Length of line. */
double length;
/** Number of pixels in the line's support. */
unsigned int num_pixels;
/** Number of pixels who voted for line. */
unsigned int num_votes;
/** Slope in the x-direction. */
double tangent_x;
/** Slope in the y-direction. */
double tangent_y;
/** Midpoint in the x-direction. */
double midpoint_x;
/** Midpoint in the y-direction. */
double midpoint_y;
} Line;
然後就是組成所有線的vector。
vector<Line*> vLines;
尖括號中是要存入的資料型別,可以是int、string等預設的,也可以是自定義的類或者結構體,我們存的就是自定義的Line型別。
使用vector這資料型別,需要標頭檔案 #include <vector>,並且記得using namespace std;
1、將元素插入vector
Line* line;//初始化一條直線line->x1 = 0;
line->y1 = 0;
line->x2 = 10;
line->y2 = 10;
line->length = abs(line->x1 - line->x2)/2+ abs(line->y1 - line->y2)/2;
vLines.push_back(line);//將直線插入vecotr
2、獲取vector的大小
int vNum = vLines.size();
3、遍歷和索引vector中的元素
有兩種索引方式,一種是定義整型的迴圈變數i,然後用中括號或者at的方法獲取i位置的元素。
for (i = 0;i<vSize;i++){
Line* line = vLines.at(i);//或者用Line* line = vLines[i];
double length = line->length; //獲取該元素的長度
} 另一種是定義迭代器變數,利用vector的begin()和end()獲取開始和結束條件。 for (vector<Line*>::iterator ri=vLines.begin();ri!=vLines.end();ri++)
{
Line* line = *ri;
int length = line->length;
}
4、刪除vector中的元素
刪除的方法目前我只知道通過erase的方式,但是erase只支援迭代器,所以如果想刪除只會用上面提到迭代器的方式索引vector中的元素
vLines.erase(ri);