-1

I am very new to C++ and I try to understand a large project. Here's where I'm stuck,I want to index container class without for-each.

There's this method returns pointer of a container class Bars:

virtual Bars* getBarsPtr()              { return &bars_; }

In the code, each element are accessed by for-each, and it works. Bar is the element of for-each. The code is in the following:

for (auto& bar : *foo_.getBarsPtr()) {

getBarsPtr() returns the pointer to Bars. The thing I am wondering, how can I access each 'bar' without for-each.

UPDATE: As SergeyA answered, this container did not provide indexed access. Regards

oguz
  • 3
  • 3
  • Unrelated to your question, but I think you should take some time to [read a few good beginners books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn about *references*. – Some programmer dude Jul 31 '17 at 18:24
  • As for your problem, what *is* the problem? Why do you want to iterate over the vector using indexes (which is something any [good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) would show you)? What's wrong with the range-based `for` loop? What's wrong with using iterators? – Some programmer dude Jul 31 '17 at 18:26
  • http://en.cppreference.com/w/cpp/language/range-for – Justin Jul 31 '17 at 18:26
  • Lastly, please take some time to [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and learn how to create a [Minimal, **Complete**, and Verifiable Example](http://stackoverflow.com/help/mcve). What is `Bars`? What is `Baz`? – Some programmer dude Jul 31 '17 at 18:29
  • Thanks! I will follow these. Issue resolved, but question updated anyways. – oguz Jul 31 '17 at 21:56

1 Answers1

0

A ranged for loop is not necessarily convertable to indexed access. However, it is always convertable to iterator access, because this is what it is.

Every ranged for loop is equal to following:

for (auto it = std::begin(bar), e = std::end(bar); it != e; ++it) {
}

But not every container provides for indexed access! The simplest example is the list. You can't access element number 5 of the list, you can only access next and previous elements of the current one. This is the basic idea behind this structure.

I would imagine, your data structure is of the same quality (you never provide the actual structure!) in what it defines begin and end member, but doesn't provide an override for operator[], which would be required for indexed access.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Thank you very much, @SergeyA! Exactly as you said, "it defines begin and end member, but doesn't provide an override for operator[], which would be required for indexed access." – oguz Jul 31 '17 at 21:47