2013-01-10 68 views
0

如果我有一個因素功能f構建STL容器聲明之後

typedef std::vector<int> IntVec; 
const IntVec f(...) { 
    IntVec retval; 
    ... 
    return retval; 
} 

,我需要聲明後延遲的定義如下:

IntVec instance; 
if (...) { 
    instance = f(a, ...); 
} 
else { 
    instance = f(b, ...); 
} 

是否有建議的方式來做到這一點?現在


,我用容器的指針要做得像:

std::auto_ptr<IntVec> pinstance(NULL); 
if (...) { 
    pinstance.reset(new IntVec(f(a, ...))); 
} 
else { 
    pinstance.reset(new IntVec(f(b, ...))); 
} 
IntVec& instance(*pinstance); 

有沒有更好的辦法?

感謝

回答

3

IntVec retval;

這一切是創建一個空的載體。它已經初始化,但是就內容而言,它是空的,你可以在你認爲合適的時候添加它。

此外,

IntVec instance; 
if (...) { 
    instance = f(a, ...); 
} 
else { 
    instance = f(b, ...); 
} 

這是合法的。

實例不會被f的返回覆蓋,但效率命中可以忽略不計,我懷疑你經常使用這個函數。你

也可以做這樣的事情..

IntVec instance = f(...?a:b,...); 
        //if 

如果你顯示它您if語句一樣簡單。

終於你用指針的例子有缺陷

我猜pinstance即將instance之前被破壞,在這種情況下instance成爲晃來晃去參考

+0

雅,你是對的。我的例子需要程序員照顧懸而未決的參考。 – wush978

+0

順便說一句,是 IntVec實例; instance = f(...); 效率與 IntVec實例(f(...)); ? – wush978

+0

@ wush978我不確定。我相信所有的差異都是無關緊要的。你可以運行測試來檢查。 –

1

使用C++ 11,交換可以非常有效的,如果你的數據類型支持移動賦值:

#include <iostream> 
#include <vector> 
#include <string> 
#include <ctime> 
using namespace std; 

int main() 
{ 
    std::vector<int> inst; 
    std::srand((unsigned)time(0)); 

    // code to set condition. 
    if (rand()%2) 
    { 
     std::vector<int> v1(10,10); 
     std::swap(inst, v1); 

     cout << "V1" << endl; 
     std::copy(v1.begin(), v1.end(), ostream_iterator<int>(cout,"\n")); 
    } 
    else 
    { 
     std::vector<int> v2(11,11); 
     std::swap(inst, v2); 

     cout << "V2" << endl; 
     std::copy(v2.begin(), v2.end(), ostream_iterator<int>(cout,"\n")); 
    } 

    cout << "Instance" << endl; 
    std::copy(inst.begin(), inst.end(), ostream_iterator<int>(cout,"\n")); 

    return 0; 
} 

輸出

V2 
Instance 
11 
11 
11 
11 
11 
11 
11 
11 
11 
11 
11 

注意,在V2沒有內容,因爲它有與空矢量inst交換。

看起來你已經掌握了懸掛的參考,所以我會在問題的第二部分留下來。