[英]Simplify std::string construction involving concatenating integers in C++
尋找更優雅的快捷方式:
for (int i=1; i<=maxNum; i++)
{
std::ostringstream s;
s << i;
std::string group1 = "group1_" + s.str();
std::string group2 = "group2_" + s.str();
.
.
.
val = conf->read(group1.c_str());
.
.
.
}
任何人都可以想到一種優雅的方式,例如:
conf->read({SOMEMACRO or function}("group1_", i));
可以使用內置的C ++工具來完成此操作嗎? 順便說一句,提高不是一個選擇。
為什么不這樣:
inline std::string construct_group_id(int n, int i)
{
std::ostringstream s;
s << "group" << n << "_" << i;
return s.str();
}
我想我會使用Boost(有點受限制)的lexical_cast副本:
template <class T, class U>
T lexical_cast(U const &input) {
std::stringstream buffer;
buffer << input;
T ret;
buffer >> ret;
return ret;
}
for (int i=0; i<maxNum; i++)
val = conf->read("group1_" + lexical_cast<std::string>(i));
這是圍繞itoa
的靜態包裝。 它不是線程安全的。
static const char * static_itoa( const int val )
{
static char buff[20];
return itoa( val, buff, 10 );
}
這是一個小幫手功能來完成這項工作:
inline std::string myitoa(size_t n)
{
std::string res = n ? "" : "0";
while(n) { res += '0' + (n % 10); n /= 10; }
return std::string(res.rbegin(), res.rend());
}
for (size_t i = 0; i < N; ++i)
{
const std::string n = myitoa(i+1);
std::string g1 = "group1_" + n;
/* ... */
}
這要求您進行編碼以連續存儲數字字符,並且N小於10。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.