C++ equivalent of StringBuffer/StringBuilder?

前端 未结 10 919
说谎
说谎 2020-11-29 15:51

Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#\'s StringBuilder or Java\'s StringBuffer?

10条回答
  •  清歌不尽
    2020-11-29 16:20

    NOTE this answer has received some attention recently. I am not advocating this as a solution (it is a solution I have seen in the past, before the STL). It is an interesting approach and should only be applied over std::string or std::stringstream if after profiling your code you discover this makes an improvement.

    I normally use either std::string or std::stringstream. I have never had any problems with these. I would normally reserve some room first if I know the rough size of the string in advance.

    I have seen other people make their own optimized string builder in the distant past.

    class StringBuilder {
    private:
        std::string main;
        std::string scratch;
    
        const std::string::size_type ScratchSize = 1024;  // or some other arbitrary number
    
    public:
        StringBuilder & append(const std::string & str) {
            scratch.append(str);
            if (scratch.size() > ScratchSize) {
                main.append(scratch);
                scratch.resize(0);
            }
            return *this;
        }
    
        const std::string & str() {
            if (scratch.size() > 0) {
                main.append(scratch);
                scratch.resize(0);
            }
            return main;
        }
    };
    

    It uses two strings one for the majority of the string and the other as a scratch area for concatenating short strings. It optimise's appends by batching the short append operations in one small string then appending this to the main string, thus reducing the number of reallocations required on the main string as it gets larger.

    I have not required this trick with std::string or std::stringstream. I think it was used with a third party string library before std::string, it was that long ago. If you adopt a strategy like this profile your application first.

提交回复
热议问题