简体   繁体   中英

How the ++ operator of the const_iterator works for vector<string> in C++ standard library?

String size is not fixed. How they made iterator knows where to point to after the increment?

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  vector<string> myVector{"ABC", "DEF"};

  for (auto p = myVector.begin(); p != myVector.end(); ++p)
    cout << *p << endl;
}

In fact, sizeof(std::string) is fixed. The actual string data (which is not of fixed size) is stored elsewhere in memory, and the std::string object only contains a pointer to it.

So an iterator over std::vector<std::string> can simply advance by sizeof(std::string) bytes at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM