Is there a C++ iterator that can iterate over a file line by line?

EDIT: This same trick was already posted by someone else in a previous thread. It is easy to have std::istream_iterator do what you want: namespace detail { class Line : std::string { friend std::istream & operator>>(std::istream & is, Line & line) { return std::getline(is, line); } }; } template<class OutIt> void read_lines(std::istream& is, OutIt dest) … Read more

Should custom containers have free begin/end functions?

There are several approaches, each with their own pros and cons. Below three approaches with a cost-benefit analysis. ADL through custom non-member begin() / end() The first alternative provides non-member begin() and end() function templates inside a legacy namespace to retrofit the required functionality onto any class or class template that can provide it, but … Read more

c++11 foreach syntax and custom iterator

To be able to use range-based for, your class should provide const_iterator begin() const and const_iterator end() const members. You can also overload the global begin function, but having a member function is better in my opinion. iterator begin() and const_iterator cbegin() const are also recommended, but not required. If you simply want to iterate … Read more

How to avoid code duplication implementing const and non-const iterators?

[The best answer was, unfortunately, deleted by a moderator because it was a link-only answer. I understand why link-only answers are discouraged; deleting it, however, has robbed future seekers of very useful information. The link has remained stable for more than seven years and continues to work at the time of this writing.] I strongly … Read more

How to iterate over a std::map full of strings in C++

Your main problem is that you are calling a method called first() in the iterator. What you are meant to do is use the property called first: …append(iter->first) rather than …append(iter->first()) As a matter of style, you shouldn’t be using new to create that string. std::string something::toString() { std::map<std::string, std::string>::iterator iter; std::string strToReturn; //This is … Read more