2012-04-19 29 views
5
void PrintNow(const std::vector<int> &v) 
{ 
    std::cout << v[0] << std::endl; 
} 

std::vector<int>().push_back(20); // this line generates no complains 
PrintNow(std::vector<int>().push_back(20)); // error 

從VS2010 SP1:我們可以創建臨時傳入`std :: vector <int>`參數嗎?

eror C2664: 'PrintNow':不能轉換參數1從 '無效' 到 '常量性病::矢量< _Ty> &'

Q >我們可以通過臨時向量來運行嗎?

回答

8

在C++ 11,你可以這樣做:

void PrintNow(const std::vector<int> &v) 
{ 
    std::cout << v[0] << std::endl; 
} 

PrintNow({20}); 

VS2010還不支持這一部分C++ 11雖然。 (GCC 4.4和3.1鏗鏘做)

如果您只需要在C++ 03然後一個單一的元素,你可以這樣做:

PrintNow(std::vector<int>(1,20)); 

如果你需要一個以上的元素話,我不認爲有任何一種線路解決方案你可以這樣做:

{ // introduce scope to limit array lifetime 
    int arr[] = {20,1,2,3}; 
    PrintNow(std::vector<int>(arr,arr+sizeof(arr)/sizeof(*arr)); 
} 

或者你可以寫一個可變參數的函數,它接受整型的列表,並返回一個載體。除非你使用了很多,但我不知道它是否值得。

+0

至少在GCC 4.4.5中支持'{20}'語法。 – 2012-04-19 14:50:05

+0

在C++ 03中,你可以使用['boost :: list_of'](http://www.boost.org/doc/libs/1_39_0/libs/assign/doc/index.html#list_of)沒有額外的命名變量的在線解決方案。 – 2012-04-19 15:11:23

4

問題是std::vector::push_back()返回void,而不是你不能通過臨時函數。

+0

'void vector :: push_back(const T&x)' – q0987 2012-04-19 14:44:12

+2

@ q0987正好......因此它返回'void' ... – 2012-04-19 14:45:03

3

如果所有元素都是相同的價值,你有適合您的需要一個構造函數:

PrintNow(std::vector<int>(1,20)); 
4

生成該錯誤,因爲std::vector::push_back函數的返回類型爲void

void push_back (const T& x); 

請嘗試以下操作:

PrintNow(std::vector<int>(1, 20)); 

The co上面去使用std::vector類可用的構造函數:

explicit vector (size_type n, const T& value= T(), const Allocator& = Allocator()); 
相關問題