1
  1. We can construct a vector to store a bunch of strings by writing vector, but a string is can be variable length, how can vector deal with that?
  2. I also test a demo, test[0] begin with 0x2508cb0, test[1] begin with 0x2508cb8, but the diff of two addresses and the capacity of test[0] seems to be not same.

int main() {

vector<string> test;
test.push_back("tes3235235et");
test.push_back("135125151241241241");
cout << test[0].capacity() << endl;
cout << test[1].capacity() << endl;
cout << &(test[0]) << endl;
cout << &(test[1]) << endl;
return 0;

}

Output:

12
18
0x2508cb0
0x2508cb8

1
  • 3
    String objects all have the same size, it is the size of the data that is stored by string objects (and probably stored on the heap) may vary. Commented Nov 11, 2017 at 19:14

1 Answer 1

5

The vector doesn't need to deal with that, because the string deals with that. Just like std::vector, std::string stores its elements in dynamically allocated memory. The characters are not part of the string object itself (except in the case of small string optimization), but are instead just referred to via a pointer. The actual size of the string object is set at compile time and is the same for all strings (and can be obtained by sizeof(std::string)), regardless of the number of characters.

Sign up to request clarification or add additional context in comments.

1 Comment

"The vector doesn't need to deal with that, because the string deals with that." Right, and that's kinda the whole point of classes and objects. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.