Is it safe to use negative integers with size_t?

后端 未结 4 1803
旧巷少年郎
旧巷少年郎 2021-02-20 17:52

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, b

4条回答
  •  眼角桃花
    2021-02-20 18:23

    I can't speak to how safe that code is but I think it's a pretty poor style. A better way would be to use iterators which support forward or reverse iteration.

    For example:

    std::vector v = { 1, 2, 3, 4, 5 };
    bool rev = true;
    
    if (rev)
    {
        for (auto itr = v.rbegin(); itr != v.rend(); ++itr)
        {
            std::cout << *itr << "\n";
        }
    }
    else
    {
        for (auto itr = v.begin(); itr != v.end(); ++itr)
        {
            std::cout << *itr << "\n";
        }
    }
    

提交回复
热议问题