JohhnieWH JohhnieWH - 1 year ago 93
C++ Question

Range-for loop with custom class(simple version of vector<string>,using allocator)

I'm currently going through C++ Primer 5th Ed. and today I've reached the chapter about classes that deal with dynamic memory. Given, the following concept:

class StrVec{


StrVec() : // the allocator member is default initialized
cap(nullptr) {}

StrVec(const StrVec&);


StrVec& operator=(const StrVec&);

std::string* begin() const { return elements; }
std::string* end() const { return first_free; }
//other functions


std::allocator<std::string> alloc;

std::string *elements;

std::string *first_free;

std::string *cap;

//other functions


And a
StrVec foo={"stack","overflow"}
, how does a range-for loop work exactly (
for(auto& el : foo) std::cout<<el<<std::endl
). What's the "thing" that I'm iterating through?

Answer Source

What's the "thing" that I'm iterating through?

The range that is delimited by the result of foo.begin() and foo.end().

Yes, these function names are "special" in that regard. Call it a standard-approved convention.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download