首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将对象推回到std::vector

将对象推回到std::vector
EN

Stack Overflow用户
提问于 2018-12-18 00:25:33
回答 1查看 174关注 0票数 0

我在用c++编写一个子弹系统。我在c++方面经验不是很丰富。

对于我的bullet系统,我想要有一个bullet管理器类,用于更新和绘制所有的bullet。我还有一个叫做' bullet‘的类,它就是一个子弹头。

代码语言:javascript
复制
class Bullet {
public:
    Bullet();

    sf::Sprite bullet_sprite;
    sf::Vector2f movement_vector;
    sf::Vector2f destination_pos;
    float speed;
};


class BulletManager : public Entity {
public:
    virtual void draw(sf::RenderWindow& window);
    virtual void update(sf::RenderWindow& window);

    std::vector<Bullet*> bullets;

};

我把每一颗子弹都存储在一个向量中。在绘图和更新函数中,我遍历此向量并对每个项目符号执行必要的操作。

我很难从我的player类中添加项目符号到矢量中。我试图像这样传递一个对新项目符号的引用:

代码语言:javascript
复制
bullet_manager.bullets.push_back(&bullet);

但是,项目符号向量的大小始终保持为零。

如何将player类中的新bullet对象添加到此向量中?

还有-我在player类中有这个,因为它是‘处理播放器输入’函数的一部分。

EN

回答 1

Stack Overflow用户

发布于 2018-12-18 05:08:59

尝试使用std::move()

请检查此链接!

https://es.cppreference.com/w/cpp/utility/move

并查看链接中的示例:

代码语言:javascript
复制
#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;

    // uses the push_back(const T&) overload, which means 
    // we'll incur the cost of copying str
    v.push_back(str);
    std::cout << "After copy, str is \"" << str << "\"\n";

    // uses the rvalue reference push_back(T&&) overload, 
    // which means no strings will copied; instead, the contents
    // of str will be moved into the vector.  This is less
    // expensive, but also means str might now be empty.
    v.push_back(std::move(str));
    std::cout << "After move, str is \"" << str << "\"\n";

    std::cout << "The contents of the vector are \"" << v[0]
                                         << "\", \"" << v[1] << "\"\n";
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53819223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档