Simplify std::string construction involving concatenating integers in C++

做~自己de王妃 提交于 2019-12-12 02:18:13

问题


Looking for a more elegant shortcut to the following:

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());
   .
   .
   .
}

Can anyone think of an elegant way like:

conf->read({SOMEMACRO or function}("group1_", i));

Can this be done in place with a built-in C++ facility? Btw, boost is not an option.


回答1:


Why not something like:

inline std::string construct_group_id(int n, int i)
{
    std::ostringstream s;
    s << "group" << n << "_" << i;
    return s.str();
}



回答2:


I think I'd use a (somewhat restricted) copy of Boost's 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));



回答3:


This is a static wrapper around itoa. It is not thread-safe.

static const char * static_itoa( const int val )
{
    static char buff[20];
    return itoa( val, buff, 10 );
}



回答4:


Here's a little helper function to do the trick:

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;
  /* ... */
}

This requires your encoding to store the numeral characters contiguously and N less than 10.



来源:https://stackoverflow.com/questions/6495220/simplify-stdstring-construction-involving-concatenating-integers-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!