for each
oświadczenie w VC++, kiedy jest stosowany na nie zarządzane Klasa:
for each (T x in xs)
{
...
}
jest po prostu cukier syntaktyczny na to:
for (auto iter = xs.begin(), end = xs.end(); iter != end; ++iter)
{
T x = *iter;
}
Gdzie auto
oznacza, że typ zmiennej jest wyprowadzona automatycznie typ inicjalizatora.
Innymi słowy, musisz podać metody klasy begin()
i end()
, które zwróciłyby dla niego początkowe i końcowe iteratory wejściowe.
Oto przykład z klasy, która owija się istream
i umożliwia iteracyjne nad wszystkie linie w nim:
#include <istream>
#include <iostream>
#include <fstream>
#include <string>
class lines
{
public:
class line_iterator
{
public:
line_iterator() : in(0)
{
}
line_iterator(std::istream& in) : in(&in)
{
++*this;
}
line_iterator& operator++()
{
getline(*in, line);
return *this;
}
line_iterator operator++ (int)
{
line_iterator result = *this;
++*this;
return result;
}
const std::string& operator*() const
{
return line;
}
const std::string& operator->() const
{
return line;
}
friend bool operator== (const line_iterator& lhs, const line_iterator& rhs)
{
return (lhs.in == rhs.in) ||
(lhs.in == 0 && rhs.in->eof()) ||
(rhs.in == 0 && lhs.in->eof());
}
friend bool operator!= (const line_iterator& lhs, const line_iterator& rhs)
{
return !(lhs == rhs);
}
private:
std::istream* const in;
std::string line;
};
lines(std::istream& in) : in(in)
{
}
line_iterator begin() const
{
return line_iterator(in);
}
line_iterator end() const
{
return line_iterator();
}
private:
std::istream& in;
};
int main()
{
std::ifstream f(__FILE__);
for each (std::string line in lines(f))
{
std::cout << line << std::endl;
}
}
Należy zauważyć, że realizacja line_iterator
jest faktycznie nieco większy niż minimum potrzebnego for each
; Jednakże, jest to minimalna realizacja zgodnych z wymaganiami iterator wejściowy, a więc klasa ta jest również użyteczny ze wszystkich algorytmów STL, które działają na iteratorów wejściowych, takich jak std::for_each
, std::find
itp
MS kompilator nigdy obsługiwany anyting tak dla kodu C++. Sądzę, że mówisz o jakimś innym języku. DO#? Jeśli tak, musisz powtórzyć swoje pytanie. – AnT
http://msdn.microsoft.com/en-us/library/ms177202%28VS.80%29.aspx – stelonix
Być może tag C++ powinien być tagiem vC++. Z pewnością nie jest to standardowe pytanie w języku C++. – MAK