3

I wondered if that would be possible, a custom for loop. The one I had in mind was the foreach expression from java, which is

for(Container c : Element e){
      // do stuff with e
} 

I wanted to write it for a custom container I wrote (lets call it cust_cont), which I wanted to work with a foreach loop (like the one from boost). But before reading into iterators and such, I wanted to ask wether I can just implement the loop I want, if need explicitly.

2
  • 3
    If you are using C++0x that is already a feature. Else i'd guess not, at least not using the for keyword, since that expects another syntax. Commented Aug 8, 2011 at 8:46
  • @RedX: I think the question is about using the syntax without implementing iterators for the custom container. Commented Aug 8, 2011 at 10:00

4 Answers 4

4

Not sure I understand your question, but yes, you have to implement begin() and end() methods (ideally overloaded on const) in order for iteration to work on your custom container. Also, you need nested iterator and const_iterator types (or typedefs). To summarize, here is what you need:

member types:

MyClass::iterator
MyClass::const_iterator

member functions:

MyClass::iterator MyClass::begin();
MyClass::const_iterator MyClass::begin() const;
MyClass::iterator MyClass::end();
MyClass::const_iterator MyClass::end() const;
Sign up to request clarification or add additional context in comments.

Comments

3

Such loop is called range-based loop which is a feature added in C++0x.

So in C++0x, you can write this:

for(Element e : c) {
      // do stuff with e
} 

where c is a container of object of type Element, and which has defined begin and end as member functions, OR can be passed to begin() and end() functions which are looked up with argument-dependent lookup (ADL), and std is one of the associated namespace(s).

4 Comments

I never knew that worked.. I guess I should read the 0x documentation more thoroughly. Thanks
@Nawaz: is it std::begin and std::end, or is it a free function begin and end that can be found via typical ADL ? swap uses ADL, for example.
@Matthieu: You are right. They're looked up with ADL. Edited the answer. Thanks :-)
@Nawaz: I am still fuzzy on C++0x, I blame the lack of experience :D I note that Clang 3.0 seem to provide it though, nice :D
0

you can write a macro, something like this:

foreach(Element, e, c) { ... }

Comments

0

See fredoverflow's answer on how to do this for a custom container but since c++11 this became even easier using auto

for(auto element : container)
    //do something with element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.