Benefits of vector over string?

后端 未结 7 1504
自闭症患者
自闭症患者 2020-12-14 09:52

This question is related to, but not quite the same as, this question.

Are there any benefits to using std::vector instead of std::str

7条回答
  •  旧时难觅i
    2020-12-14 09:56

    As other answers mention, a vector could be marginally faster since it guarantees contiguous memory, even for small sizes, and doesn't add an extra null byte at the end. However, it is a lot simpler (code-wise) to concatenate two strings than it is to concatenate two vectors:

    Using vector:

    vector a, b;
    // ...
    vector c;
    c.insert(c.end(), a.begin(), a.end());
    c.insert(c.end(), b.begin(), b.end());
    

    Using string:

    string a, b;
    // ...
    string c = a + b;
    

提交回复
热议问题