c++ - 将unique_ptr vector 分配给 vector C++

标签 c++ unique-ptr

我目前正在尝试将动态的脚步音频合并到我的游戏中。这里是一些代码:

class MyClass
{
    vector< unique_ptr <Sound> > footstep_a;
    vector< unique_ptr <Sound> > footstep_b;
    vector< unique_ptr <Sound> > footstep_c;
    vector< Sound > currentfootsteps;
}

因此,基本上我想做的就是将footstep_ vector 之一分配给currentfootsteps,这样我就可以拥有:
if( walkingarea == a )
    currentfootsteps = a;
else ......

我已经尝试过执行以下操作,但它只会在 vector 等方面引发一百万个错误:
if ( walkingarea == a )
    currentfootsteps.clear();
    for(int i = 0; i < footstep_a.size(); i++)
        currentfootsteps.push_back( footstep_a[i] );

谁能帮我?

最佳答案

我不太了解您要做什么,但是假设Sound类是可复制的,则可以编译:

currentfootsteps.clear();
for(auto const& up : footstep_a) {
    currentfootsteps.push_back(*up);
}

请注意,您正在复制footstep_a中的每个元素,并将其添加到currentfootsteps中。

如果Sound是仅移动的,或者您想避免复制,请改用此方法:
currentfootsteps.clear();
for(auto&& up : footstep_a) {
    currentfootsteps.push_back(std::move(*up));
}

但是似乎您也可以通过使currentfootsteps成为指针,并根据满足的条件简单地指向vector之一来避免所有这些情况。
vector< unique_ptr <Sound> > *currentfootsteps = nullptr;

if ( walkingarea == a ) {
  currentfootsteps = &footstep_a;
} else if ...

关于c++ - 将unique_ptr vector 分配给 vector C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419100/

相关文章:

c++ - 如何安全地重载 std::unique_ptr 的自定义删除器?

c++ - unique_ptr<T>.get() 方法在使用原始指针分配时调用析构函数?

java - 无法运行程序 "\ndk-build.cmd": Launching failed

c++ - 小数点不显示

c++ - 在启动期间崩溃时如何使用 gdb 调试可执行文件?

C++如何在有限的时间内等待键盘输入

c++ - std::list 可以包含不同的 std::unique_ptr<T> 吗?

c++ - 类型不完整的 std::unique_ptr 将无法编译

c++ - 如何设置两个 vector<unique_ptr<...>> 彼此相等?

c++ - 可变参数模板 : One method per template argument