JohhnieWH JohhnieWH - 3 months ago 17
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{

public:

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

StrVec(const StrVec&);

StrVec(std::initializer_list<std::string>);

StrVec& operator=(const StrVec&);

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

private:

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

std::string *elements;

std::string *first_free;

std::string *cap;

//other functions

};


And a
StrVec
object
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

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.