I do really like Ranged-based-for-loop which is supported by C++11 and above. I'd like for some understanding reason to simulate it. Here is an example:
// 1
//#define ranged_for(X, T) \
//  for (std::vector<int>::iterator beg{ T.begin() },\
//      end{ T.end() }; beg != end; X = *beg, ++beg)\
// 2
//#define ranged_for(X, T) \
//  for (std::vector<int>::iterator beg{ T.begin() },\
//      end{ T.end() }; beg != end; ++beg, X = *beg)\
// 3
#define ranged_for(X, T) \
    for (std::vector<int>::iterator beg{ T.begin() },\
        end{ T.end() }; beg != end; ++beg)\
            X = *beg, 
int main(){
    std::vector<int> data{75, 435, 6578, 92, 123};
    auto i{ 0 };
    ranged_for(i, data)
        std::cout << i << std::endl;
    std::cout << std::endl;
    std::cin.get();
    return 0;
}
As you can see above the first macro doesn't get the first element 75 but instead the value 0 and the last one is not there.
- 
The second macro crashes the program that is because i think reading the last node (sentry).
 - 
The third works fine but as you can see after the macro expansion I'll get:
i = *beg, std::cout << i << std::endl; 
That is because the line above is treated as a single statement. Is there a better way and explanation. Thank you all good dudes!.
Aucun commentaire:
Enregistrer un commentaire