Prepend std::string

后端 未结 4 509
醉梦人生
醉梦人生 2021-02-06 20:03

What is the most efficient way to prepend std::string? Is it worth writing out an entire function to do so, or would it take only 1 - 2 lines? I\'m not seeing anyth

4条回答
  •  野性不改
    2021-02-06 20:50

    If you're using std::string::append, you should realize the following is equivalent:

    std::string lhs1 = "hello ";
    std::string lhs2 = "hello ";
    std::string rhs = "world!";
    
    lhs1.append(rhs);
    lhs2 += rhs; // equivalent to above
    // Also the same:
    // lhs2 = lhs2 + rhs;
    

    Similarly, a "prepend" would be equivalent to the following:

    std::string result = "world";
    result = "hello " + result;
    // If prepend existed, this would be equivalent to
    // result.prepend("hello");
    

    You should note that it's rather inefficient to do the above though.

提交回复
热议问题