基于 2D 数组初始化向量
initializing a vector based on a 2d array
我有一个Visual Studio 2008 C++03应用程序,我想基于二维数组初始化一个std::vector。
例如:
#define DATA_SIZE 6
struct Data
{
UINT a;
BYTE b;
BYTE c;
BYTE d;
Data()
: /* initialize all members to 0*/
{
};
explicit Data( const BYTE data[ DATA_SIZE ] )
: a( data[ 0 ] << 16 | data[ 1 ] << 8 | data[ 2 ] ),
b( data[ 3 ] ),
c( data[ 4 ] ),
d( data[ 5 ] )
{
};
};
inline bool operator==( const Data& lhs, const Data& rhs )
{
return /* true if all members are equal */
};
int main( int argc, char* argv[] )
{
const BYTE source[][ DATA_SIZE ] =
{
{ 0x01, 0xfe, 0xaa, 0x01, 0xcc, 0x13 },
{ 0x02, 0xa1, 0x02, 0xbb, 0x02, 0xdd }
}
// how should this be done?
std::vector< Data > data_list( source[ 0 ], source[ countof( source) - 1 ] );
ASSERT( data_list[ 0 ] == Data( source[ 0 ] ) );
ASSERT( data_list[ 1 ] == Data( source[ 1 ] ) );
return 0;
}
有没有办法在没有for
循环遍历data
数组中的每个项目并调用push_back
的情况下做到这一点?
您可以做的最少更改是:
std::vector< Data > data_list(
&source[ 0 ],
&source[ countof( source) ] );
以下是使用 Boost.Array 的方法:
#include <cstddef>
#include <cassert>
#include <vector>
#include <boost/array.hpp>
typedef unsigned UINT;
typedef unsigned char BYTE;
std::size_t const DATA_SIZE = 6;
struct Data
{
UINT a;
BYTE b, c, d;
Data() : a(), b(), c(), d() { }
Data(boost::array<BYTE, DATA_SIZE> const& data)
: a(data[0] << 16 | data[1] << 8 | data[2]),
b(data[3]),
c(data[4]),
d(data[5])
{ }
};
inline bool operator ==(Data const& lhs, Data const& rhs)
{
return lhs.a == rhs.a
&& lhs.b == rhs.b
&& lhs.c == rhs.c
&& lhs.d == rhs.d;
}
int main()
{
boost::array<boost::array<BYTE, DATA_SIZE>, 2> const source =
{{
{{ 0x01, 0xfe, 0xaa, 0x01, 0xcc, 0x13 }},
{{ 0x02, 0xa1, 0x02, 0xbb, 0x02, 0xdd }}
}};
std::vector<Data> data_list(source.begin(), source.end());
assert(data_list[0] == Data(source[0]));
assert(data_list[1] == Data(source[1]));
}
在线演示。
相关文章:
- 为什么我在向量初始化时收到此错误?
- 使用向量初始化参数化构造函数的对象数组
- C++向量初始化遗传算法的代理向量
- shared_ptr类的向量的向量初始化问题
- 如何实现使用 gcc-4.4 编译的大向量初始化?
- 使用向量初始化C++中的链表
- C++ 中的向量初始化
- 如何使用嵌套初始化构造函数中的一维向量初始化矩阵
- std::另一个函数中的向量初始化
- 理解向量初始化时出现问题
- 静态常量 std::<char>没有堆的向量初始化?
- 向量初始化在 C++ 类中失败
- 具有从特定范围的随机数初始化特征矩阵或向量初始化特征矩阵或向量的有效方法
- 关于向量初始化的一些问题
- 了解C 中的向量初始化
- 设置::使用数字中的引号进行向量初始化
- VS2010中的向量初始化
- C++:构造函数中的向量初始化
- 如何从向量初始化数组?(如何将指针强制转换为数组?)
- 给我一个向量初始化的提示或(答案)