在我使用std::vector
编写的大多数程序中,我的大部分痛苦都在转换
int offset=(int)v.size();
unsigned int offset=(unsigned int)v.size();
令人遗憾的是,此类问题反射(reflect)在许多其他问题中,例如 this .
有什么方法可以重新连接 std::vector
并强制它以 int
或 unsigned int
之类的形式给出大小?
int offset=v.size_i();
类型转换使代码变得更加困惑。虽然,一些程序员喜欢它们并且觉得每次转换都没有问题。
c++14
解决方案更受青睐,但也欢迎使用 c++17
解决方案。
如果有人建议更改变量的类型,迟早必须进行另一种类型转换。所以并没有解决问题。
请考虑这些丑陋的短语
function((int)myvar1.vec[32].size(),(int)myvar2.vec[32].size());
其中 function
只接受 int
。而且我无法控制它的定义。
最佳答案
您可以继承std::vector
并重新实现size()
函数以返回有符号值:
template<typename T, typename Alloc = std::allocator<T> >
class my_vector : public std::vector<T, Alloc>
{
using base_t = std::vector<T,Alloc>;
public:
using base_t::vector;
using base_t::operator =;
int size() const noexcept { return base_t::size(); }
};
关于c++ - std::vector::size 返回一个 int 类型或 unsigned int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335530/