Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use std::vector<MyClass>

I’m having problem with using vectors of my own class. My intension is to create a new object on every spacebar click. I've already written some code:

classes.h

class someClass
{
public:
    short x;
    short y;
    someClass::someClass();
};

classes.cpp

someClass::someClass()
{
    x = 0;
    y = 0;
}

main.cpp

using namepsace std;    
vector<someClass> vMyVector;
(...)
case SDLK_SPACE:
    vMyVector.push_back();
break;

I also tried put that extra line in case SDLK_SPACE:

someClass *temp = new someClass(); 
vMyVector.push_back(temp);

But in both situations compiler return errors like

error C3867: 'std::vector<_Ty>::push_back': function call missing argument list; use '&std::vector<_Ty>::push_back' to create a pointer to member with [_Ty=someClass]

I've already spend about an hour on searching some books and reading various topics on the Internet, but none of them were useful. I put my hope in you guys!

like image 481
Greg Witczak Avatar asked Mar 14 '26 14:03

Greg Witczak


2 Answers

In the first case you're missing an argument to push_back,. It should be an instance of SomeClass, not a pointer to SomeClass, which, incidently, is the problem in the second case.

EDIT: If you just want to add an element, constructed with the default constructor, you can just do

v.resize (v.size () + 1)

and refer t the new object with

v.back ()
like image 88
chill Avatar answered Mar 17 '26 03:03

chill


You declared the vector containing objects of someClass but tried to add a pointer.

Write instead

someClass *temp = new someClass(); 
vMyVector.push_back(*temp);

or

someClass temp; 
vMyVector.push_back(temp);
like image 37
AndersK Avatar answered Mar 17 '26 02:03

AndersK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!