1

I want to use c++ 11 "for loop" to iterate elements of a vector but i receive some errors ( begin() and end() functions i think is a problem).Thanks!

#include <iostream>
#include <vector>
#include<iterator>
using namespace std;
template<typename TElement>
class MyClass {
private:
     vector<TElement> vec;
public:

MyClass& operator+(TElement n) {
     vec.push_back(n);
     return *this;
}
int getS() {
     return vec.size();
}
iterator begin() {//here is some problems
     return vec.begin();
}
iterator end() {
     return vec.end();
}
};

int main() {
    MyClass<int> mm;
    mm = mm + 10; 
    mm = mm + 9;
    double avg = 0.0;
    for (auto g : mm) { //begin() and end() functions error
       avg += mm;
    }
    cout<< avg / mm.getS();
    return 0;
}

errors:

C2675 unary '++': 'std::iterator' does not define this operator or a conversion to a type acceptable to the predefined operator,

illegal indirection,

C2678 binary '!=': no operator found which takes a left-hand operand of type 'std::iterator' ,

C2955 'std::iterator': use of class template requires template argument list,

C2514 'std::iterator': class has no constructors

paulc
  • 125
  • 6
  • [It's not as simple as that](https://stackoverflow.com/questions/8054273/how-to-implement-an-stl-style-iterator-and-avoid-common-pitfalls). – Ken Y-N Jun 10 '16 at 08:12
  • 1
    Possible duplicate of [c++11 foreach syntax and custom iterator](http://stackoverflow.com/questions/7562356/c11-foreach-syntax-and-custom-iterator) – Ken Y-N Jun 10 '16 at 08:18
  • 2
    You should always include the actual, complete, error messages. – renefritze Jun 10 '16 at 08:19

2 Answers2

0

Your begin and end functions need to be like this:

typename vector<TElement>::iterator begin() {
  return vec.begin();
}

typename vector<TElement>::iterator end() {
  return vec.end();
}

That's the actual iterator type that the vector returns. By contrast, std::iterator is a completely different and unrelated type.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0
    typedef typename vector<TElement>::iterator Iterator;

    Iterator begin() {//here is some problems
        return vec.begin();
    }

    Iterator end() {
        return vec.end();
    }

This will be better.

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

we need make sure vector<TElement>::iterator is a type, not a variable.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67