簡體   English   中英

如何初始化std :: stringstream?

[英]How to initialize a std::stringstream?

我需要將字符串與整數連接起來。 為此,我使用stringstream以下列方式:

int numPeople = 10;
stringstream ss;
ss << "Number of people is " << numPeople;

這很有效。 但我試圖通過以下方式做到:

int numPeople = 10;
stringstream ss << "Number of people is " << numPeople;

我收到以下錯誤:“ '''令牌之前的預期初始化程序

為什么我收到此錯誤? 為什么我不能在聲明它的同時分配stringstream值?

stringstream ss << "Number of people is " << numPeople;

為什么我不能在聲明它的同時分配stringstream值?

這類似於希望這可以工作:

int x + 3 + 9;

問題

當您為對象定義和賦值時,C ++允許您調用構造函數,這需要以逗號分隔的表達式列表。 為方便起見, Type variable = value; 符號被省略調用Type variable(value); ,但僅適用於單個值。

對於int ,您可以輕松更正代碼:

int x = 3 + 9;

......它的工作原理是因為“3 + 9”可以先獨立評估,以便在x存儲一個合理的值。 編譯器對int的operator +的行為做了我們想要的 :它產生我們想要存儲在xint結果。 但是,如果你嘗試使用stringstream ...

stringstream ss = "Number of people is " << numPeople;  // BROKEN

...它不起作用,因為"Number of people is " << numPeople需要首先評估但是非法 - 你會得到一個錯誤,如“ error C2296: '<<' : illegal, left operand has type 'const char [20]' “ - 它不會為stringstream構造函數提供有用的值。 問題是編譯器仍在嘗試應用按位移位運算符,這只對數字有意義,因為<<我們想要應用的<<的重載需要一個類型為ostream&的左手參數。 C ++要求在=的右邊評估的值獨立於最終使用結果值完成的賦值進行求值,並且此時構造的變量的類型與對表達式進行求值的方式無關。分配。

一個辦法

這里有點雞蛋和雞蛋的問題,因為你需要在stringstream組合你想要的右手值來調用stringstream的構造函數,但為此你需要...一個stringstream 你可以用一個臨時的stringstream

static_cast<std::ostringstream&&>(std::ostringstream() << "Number of people is " << numPeople)

遺憾的是需要stringstream因為operator<< stringstream通過引用它們的ostream基類來處理stringstream ,返回一個ostream& ,所以你需要手動stringstream轉換回stringstream類型,這樣你就可以調用std::stringstream move構造函數了。 ...

那么完整的單線結構就是......

std::stringstream ss(static_cast<std::ostringstream&&>(std::ostringstream() << "Number of people is " << numPeople));

......但這太難以思考了。

使解決方案(可以說)不那么可怕

根據您的敏感度,您可能會感覺到宏有幫助或更糟糕......

#define OSS(VALUES) \
    static_cast<std::ostringstream&&>(std::ostringstream() << VALUES)

std::stringstream ss(OSS("Number of people is " << numPeople));

FWIW,您也可以使用宏來創建字符串......

std::string s(OSS("Number of people is " << numPeople).str()); 

(可以說是)更好的做法

只需創建stringstream - 可選擇為構造函數提供單個string - 然后在第二個語句中使用operator<<

std::stringstream ss;
ss << "Number of people is " << numPeople;

這更容易閱讀。 通過移動構造,在優化之后,可能沒有性能原因來選擇兩個語句。

替代

C ++ 11引入了to_string()重載,如果你有一個或兩個整數值來連接或插入string ,這是很方便的:

std::string s = "Number of people is " + std::to_string(numPeople);

這可能是低效的(如果你關心,請檢查你的編譯器優化能力):每個std::to_string()可能為獨立的std::string實例動態分配一個緩沖區,然后各個連接可能涉及額外的復制對於文本,可能需要擴大原始動態分配的緩沖區,然后大多數臨時std::string s在銷毀期間需要時間來解除分配。

在C ++ 03中更糟糕

C ++ 03缺少移動構造函數,因此有必要在臨時使用std::ostringstream::str()成員函數來獲取std::string的額外深層副本,用於構造命名的stringsteam 。 ..

stringstream ss(static_cast<std::ostringstream&>(std::ostringstream() << "Number of people is " << numPeople).str());

使用這個C ++ 03代碼,可能會出現重復的動態內存分配和內容副本,因此構建后跟流是一個更好的選擇。

必須先初始化stringbuf,然后才能將值添加到其中。 stringstream是一個對象。

通過做:

std::stringstream ss;

您實際上是允許應用程序分配空間來處理要添加的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM