【问题标题】:Which C++ std collection is most suitable for creating C style array (Foo*)? [duplicate]哪个 C++ std 集合最适合创建 C 样式数组 (Foo*)? [复制]
【发布时间】:2016-03-05 16:57:29
【问题描述】:

我正在使用的外部 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);
}

【问题讨论】:

  • std::vector::data()有什么问题吗?
  • std::vector 对象;
  • 使用 std::vector,也可以像数组一样访问
  • 因此您需要在运行时确定大小的连续对象集合。矢量有什么问题?
  • @TomášZato 列表不连续

标签: c++ arrays std


【解决方案1】:

如果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());
}

【讨论】:

  • 在插入之前对resize() 向量可能有好处。由于您没有遵循原始示例(需要对字符串进行某些操作),因此您的代码无法说明这一点。
  • @SergeyA 我没注意到。我已经更新了答案。
  • 或者,reserve 只确保有足够的空间,而不构造对象。
  • @jaggedSpire,这正是我要输入的内容。非常抱歉,resize() 在这里根本不正确。
  • @SergeyA 我已经改过了。我也时不时让他们感到困惑。
猜你喜欢
  • 2018-11-09
  • 2023-03-30
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 2011-02-19
相关资源
最近更新 更多