Search code examples
c++stliteratorstdstring

Why does string::begin exist?


If I understand correctly, string::begin returns the pointer to the first element in the string. If that is the case, why wouldn't we just use &str to get the pointer.

Are there situations where using begin is better, or have I misunderstood it's function?


Solution

  • If I understand correctly, string::begin returns the pointer to the first element in the string.

    No, it returns an iterator to the first element in the string. It helps make std::string compatible with language constructs (think templates) designed to work with standard containers.

    why wouldn't we just use &str to get the pointer.

    For one thing, that is not the address of the first element of the string? Assuming str is a variable of type std::string, that would be the address of an object that, among other things, (often) holds a pointer to the first element of the string. (If you meant the c_str() member function, then that could be done, but it's not a particularly clear and readable syntax.)