哪个 C++ std 集合最适合创建 C 样式数组 (Foo*)?
Which C++ std collection is most suitable for creating C style array (Foo*)?
我正在使用的外部 API 需要 C 样式的对象数组:
// Some api function
void doStuff(const Foo* objects, size_t length);
实际上,API 使用 int
作为长度,但这只会让情况变得更糟。创建对象数组时,我不知道我会有多少,因为有些结果是错误的:
void ObjManager::sendObjectsToApi(const std::list<const std::string>& names)
{
// Create the most suitable type of connection
std::????<Foo> objects;
// Loop names, try to create object for every one of them
for( auto i=names.begin(), l=names.end(); i<l; i++ ) {
Foo obj = createFooWithName(*i);
if( obj.is_valid() ) {
objects.addToCollection( obj );
}
}
// Convert collection to C style array
size_t length = objects.size();
Foo* c_objects = objects.toC_StyleArray();
API::doStuff(c_objects, length);
}
如果 doStuff
需要一个数组,那么我会使用 std::vector
然后使用 data()
从向量中获取数组。
std::vector<Foo> temp(names.begin(), names.end());
doStuff(temp.data(), temp.size());
std::vector
保证数据连续存储。
上面是如果你想从std::list
直接复制到std::vector
。我是你的情况,因为你正在遍历列表的内容并创建新对象,那么你将拥有
void ObjManager::sendObjectsToApi(const std::list<const std::string>& names)
{
// Create the most suitable type of connection
std::vector<Foo> objects;
objects.reserve(names.size()); // allocate space so we only allocate once
// Loop names, try to create object for every one of them
for( auto i=names.begin(), l=names.end(); i<l; i++ ) {
Foo obj = createFooWithName(*i);
if( obj.is_valid() ) {
objects.push_back( obj );
}
}
// Convert collection to C style array
API::doStuff(names.empty()? nullptr : objects.data(), objects.size());
}
我正在使用的外部 API 需要 C 样式的对象数组:
// Some api function
void doStuff(const Foo* objects, size_t length);
实际上,API 使用 int
作为长度,但这只会让情况变得更糟。创建对象数组时,我不知道我会有多少,因为有些结果是错误的:
void ObjManager::sendObjectsToApi(const std::list<const std::string>& names)
{
// Create the most suitable type of connection
std::????<Foo> objects;
// Loop names, try to create object for every one of them
for( auto i=names.begin(), l=names.end(); i<l; i++ ) {
Foo obj = createFooWithName(*i);
if( obj.is_valid() ) {
objects.addToCollection( obj );
}
}
// Convert collection to C style array
size_t length = objects.size();
Foo* c_objects = objects.toC_StyleArray();
API::doStuff(c_objects, length);
}
如果 doStuff
需要一个数组,那么我会使用 std::vector
然后使用 data()
从向量中获取数组。
std::vector<Foo> temp(names.begin(), names.end());
doStuff(temp.data(), temp.size());
std::vector
保证数据连续存储。
上面是如果你想从std::list
直接复制到std::vector
。我是你的情况,因为你正在遍历列表的内容并创建新对象,那么你将拥有
void ObjManager::sendObjectsToApi(const std::list<const std::string>& names)
{
// Create the most suitable type of connection
std::vector<Foo> objects;
objects.reserve(names.size()); // allocate space so we only allocate once
// Loop names, try to create object for every one of them
for( auto i=names.begin(), l=names.end(); i<l; i++ ) {
Foo obj = createFooWithName(*i);
if( obj.is_valid() ) {
objects.push_back( obj );
}
}
// Convert collection to C style array
API::doStuff(names.empty()? nullptr : objects.data(), objects.size());
}