I just saw some C++ code like this. It was using a condition to decide whether to walk forward or backward through a std::vector
. The compiler doesn't complain, but I thought size_t
was unsigned. Is this dangerous?
vector<int> v { 1,2,3,4,5 };
bool rev = true;
size_t start, end, di;
if (rev) {
start = v.size()-1;
end = -1;
di = -1;
}
else {
start = 0;
end = v.size();
di = 1;
}
for (auto i=start; i!=end; i+=di) {
cout << v[i] << endl;
}
Aucun commentaire:
Enregistrer un commentaire