How to append a char to a std::string?

后端 未结 13 2097
半阙折子戏
半阙折子戏 2020-11-29 15:58

The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’

int main()
{
  char d = \'d\';
  std::s         


        
相关标签:
13条回答
  • 2020-11-29 16:01

    In addition to the others mentioned, one of the string constructors take a char and the number of repetitions for that char. So you can use that to append a single char.

    std::string s = "hell";
    s += std::string(1, 'o');
    
    0 讨论(0)
  • 2020-11-29 16:07
    y += d;
    

    I would use += operator instead of named functions.

    0 讨论(0)
  • 2020-11-29 16:10

    To add a char to a std::string var using the append method, you need to use this overload:

    std::string::append(size_type _Count, char _Ch)
    

    Edit : Your're right I misunderstood the size_type parameter, displayed in the context help. This is the number of chars to add. So the correct call is

    s.append(1, d);
    

    not

    s.append(sizeof(char), d);
    

    Or the simpliest way :

    s += d;
    
    0 讨论(0)
  • 2020-11-29 16:10

    Try the += operator link text, append() method link text, or push_back() method link text

    The links in this post also contain examples of how to use the respective APIs.

    0 讨论(0)
  • 2020-11-29 16:12

    If you are using the push_back there is no call for the string constructor. Otherwise it will create a string object via casting, then it will add the character in this string to the other string. Too much trouble for a tiny character ;)

    0 讨论(0)
  • I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an i7, 8Hz, 2GHz.

        long start = clock();
        int a = 0;
        //100000000
        std::string ret;
        for (int i = 0; i < 60000000; i++)
        {
            ret.append(1, ' ');
            //ret += ' ';
            //ret.push_back(' ');
            //ret.insert(ret.end(), 1, ' ');
            //ret.resize(ret.size() + 1, ' ');
        }
        long stop = clock();
        long test = stop - start;
        return 0;
    

    According to this test, results are :

         operation             time(ms)            note
    ------------------------------------------------------------------------
    append                     66015
    +=                         67328      1.02 time slower than 'append'
    resize                     83867      1.27 time slower than 'append'
    push_back & insert         90000      more than 1.36 time slower than 'append'
    

    Conclusion

    += seems more understandable, but if you mind about speed, use append

    0 讨论(0)
提交回复
热议问题