C ++: How does random access time for vectors work?

I know that a simple vector int has O (1) random access time, since it is easy to calculate the position of the x-th element, since all elements have the same size.

Now what happens to the string vector?

Since the length of the strings is different, it cannot have O (1) random access time, right? If possible, what is its logic?

Thank.

Update:

The answers are very clear and concise, thank you all for your help. I accepted Joy's answer because it is simple and easy to understand.

+5
source share
5 answers

The vector has an access time of O (1).

String ( ) , . string , .

, s std::string, sizeof s sizeof(std::string), s.size() . sizeof(std::string).

+12

. . , O (1).

 ---------------------------
| 4000 | 4200 | 5000 | 6300 |  <- data
 ---------------------------
 [1000] [1004] [1008]  [1012]  <- address


 [4000]    [4200]    [5000]     [6300]     <- starting address
"string1" "string2" "string3"  "string4"   <- string
+5

, . , , .

+4

std::string . , , , .

+2

(, AraK), . : std::string , (SSO), , , , / , , .

As for the string vector, it does not matter: each string object has a fixed size, regardless of the length of the string itself. The difference is that with SSO, the fixed size is larger - and in many cases the string object does not have a block allocated on the heap to store the actual data.

+2
source

All Articles