我有以下代码,该代码在debug build中的界限异常,但在发行版构建中正确起作用
typedef unsigned int uint;
std::array<uint, 4> expArray = {51,639,398,744};
unsigned dataArraySize = sizeof(expArray) / sizeof(uint) ;
std::vector<uint> expected ;
std::copy(&expArray[0], &expArray[dataArraySize], back_inserter(expected));
首先使用预期的标准库:
std::vector<uint> expected(begin(expArray), end(expArray));
可悲的事实是sizeof(std::array<uint, 4>) == sizeof(uint[4])
不必保持。因此,您无法像常规C风格数组那样计算大小。
如果您希望对代码的更改最小,则使用expArray::size()
或std::tuple_size<decltype(expArray)>::value
使用begin()
和end()
方法而不是原始指针。如果要获得容器的尺寸,请使用size()
方法。
std::array<uint, 4> expArray = {51,639,398,744};
std::vector<uint> expected;
std::copy(expArray.begin(), expArray.end(), back_inserter(expected));
或更轻松的方法(不适合每种情况)
std::vector<uint> expected(std::begin(expArray), std::end(expArray));
此行是错误的:
unsigned dataArraySize = sizeof(expArray) / sizeof(uint) ;
应该是:
std::size_t dataArraySize = std::tuple_size<decltype(expArray)>::value;