標(biāo)題: stl::vector使用心得 [打印本頁(yè)]

作者: heicc    時(shí)間: 2015-1-5 14:31
標(biāo)題: stl::vector使用心得
1、同類(lèi)型vector之間拷貝數(shù)據(jù)使用push_back還是insert
此問(wèn)題貌似很搞笑,但請(qǐng)看完示例:
const   int   Num   =   5000000;
DWORD   s, d;
vector <int>   v, w( 5000000, 0 );
v.reserve(5000001);
現(xiàn)在將w中的數(shù)據(jù)全部拷貝到v中,即以下兩種情況對(duì)比:
s   =   GetTickCount();
for ( int i = 0; i < Num; ++ i )
{
        v.push_back( v[ i ] );
}
d   =   GetTickCount();

s   =   GetTickCount();
v.insert( v.end(), w.begin(), w.end() );
d   =   GetTickCount();
可以自己試試看看d-s的值,請(qǐng)多試幾次做做統(tǒng)計(jì),歸納得出insert能省一半左右的時(shí)間……
心得:vector之間拷貝數(shù)據(jù)時(shí)批量操作很省時(shí)間,但若數(shù)據(jù)量很少,其實(shí)也無(wú)所謂,當(dāng)數(shù)據(jù)量在10W以下,本身就花不了多少時(shí)間。
2、要首尾操作用vector還是deque
這個(gè)問(wèn)題貌似還要搞笑,請(qǐng)繼續(xù)看完示例:
const   int   Num   =   10000;
int  aaaaaaaa;
DWORD   s, d;
vector <int>   v,
v.reserve(5000001);
deque <int>     q;
現(xiàn)在比較下面兩段程序的運(yùn)行時(shí)間:
s   =   GetTickCount();
for   (int   i   =   0;   i   <   6000;   i++)
{
            for   (int   j   =   0;   j  <   Num;   j++)
            {
                    v.push_back(j);
            }
            for   (int  j   =   0;   j   <   Num;   j++)
            {
                    aaaaaaaa = v[j];
            }
            v.erase(v.begin(), v.end() - Num/2);
}
d   =   GetTickCount();

s   =   GetTickCount();
for   (int   i   =   0;   i   <   6000;   i++)
{
            for   (int   j   =   0;   j  <   Num;   j++)
            {
                    q.push_back(j);
            }
            for   (int  j   =   0;   j   <   Num;   j++)
            {
                    aaaaaaaa = q[j];
            }
            q.erase(q.begin(), q.end() - Num/2);
}
d   =   GetTickCount();
對(duì)比試驗(yàn)結(jié)果,讓宣稱(chēng)需要首尾操作首選的deque情何以堪,需要花費(fèi)vector十倍左右的時(shí)間。
有經(jīng)驗(yàn)的同志們仔細(xì)看看就能明白我這里模擬的是什么,對(duì),就是數(shù)據(jù)采集、讀取、刪除的不間斷操作。當(dāng)然v.reserve(5000001);語(yǔ)句功不可沒(méi)!vector連續(xù)存儲(chǔ),刪除起來(lái)自然快。
心得:批量處理,我熱愛(ài)vctor!!若需要每采集一個(gè)數(shù)據(jù)讀取刪除一個(gè),那么還是deque占優(yōu)勢(shì)的,我這里回避了deque單個(gè)處理時(shí)的pop_front()函數(shù)。
實(shí)際使用什么,自然要根據(jù)實(shí)際情況加以判斷,我寫(xiě)這些就是想發(fā)泄一下!以前一個(gè)老工程師總和我說(shuō)deque好deque快,首尾操作用deque……可在我們公司的使用現(xiàn)狀下,我不覺(jué)得deque好在哪。這也算是一個(gè)小小的抗議吧……






歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1