0

I've tried several solutions here but haven't landed on something that works for adding two std::vectors. I'm building out a game in C++ and I forward declare a fighter variable here:

class Game {
public:
    std::vector<Fighter*> fighter;
    void AddFighter(Fighter* a);

Implementing AddFighter, I need to take in a Fighter* and add it to the std::vector<Fighter*> fighter I declared. I've tried to add these vectors in a simple way like this:

void Game::AddFighter(Fighter* a) {

    fighter* = fighter* + a;
}

As well as like this referencing Appending a vector to a vector:

fighter.insert(std::end(fighter), std::begin(a), std::end(a));

However I don't think Im understanding the syntax. How do I add these vectors?

blue
  • 7,175
  • 16
  • 81
  • 179
  • 3
    Why do you want a `vector` of pointers to `Fighter`s? What owns the instances? What do you think `fighter*` means? – David Schwartz Jan 21 '22 at 07:23
  • 6
    It looks like you're learning by guessing, which is one of the worst ways to learn. Please invest in [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) and perhaps also take classes, to learn the basics of C++ properly first before attempting a non-trivial project like a game. – Some programmer dude Jan 21 '22 at 07:26
  • 2
    I want to second what was said above. You will be able to get this code to work, but it will still be terrible code, it will just be working terrible code. And that's not your fault. You don't know why a vector of pointers isn't appropriate and you haven't learned the superior alternatives. (For example, why not just `std::vector`? Why use pointers at all here?) – David Schwartz Jan 21 '22 at 07:30

1 Answers1

0

Your function implementation and what you ask for are two different things. Your function is appending a single element to the vector. For that you can use

fighter.push_back(a);

if you want to add (concatenate) two actual vectors then you can use what you have posted like this:

void AddFighters(std::vector<Fighter*> b)
{
  // for C++11+
  fighters.insert(
      fighters.end(),
      std::make_move_iterator(b.begin()),
      std::make_move_iterator(b.end())
    );
  // pre C++11
  fighters.insert(fighters.end(), b.begin(), b.end());
}

for the pre C++11 code you should also pass in the vector as const& to save on copy

ACB
  • 1,607
  • 11
  • 31
  • note the existence of `std::move` and `std::back_inserter`. i.e. there are algorithms in the std lib for the latter. – JHBonarius Jan 21 '22 at 07:41