push_back(class)

I've got a class containing 3 floats.

1
2
3
class a{
float x,y,z;
};


And I created a vector with that type.

vector<a> b;

How do I use the push_back funtion to give b 0,0,0?

i tried this:
b.push_back(0,0,0);

It didn't work...
First, your class needs a three-argument constructor:

1
2
3
4
5
class a {
    float x,y,z;
 public:
    a(float a, float b, float c) : x(a), y(b), z(c) {}
};

then you can use either

b.emplace_back(0, 0, 0);
or

b.push_back(a(0, 0, 0));

online demo: http://ideone.com/5Ngbx
Last edited on
When making x, y, z public (as they should be), you can write the following, even without creating a constructor:
b.push_back({0,0,0});
It's not working. I wrote:

b.push_back({0,0,0});

But some primary-expression is expected before "{" token.
This type of initialization and emplace_back are part of C++11. You need a recent compiler and you need to add the compiler switch -std=c++0x (GCC, ICC, clang).
What Cubbi said about constructor and push_back should work even if you have an older compiler.
Is it necessary that the floats are private then?
Last edited on
No, it doesn't matter (to the compiler, that is).
Last edited on
This is weird. It's not working but thank you anyway. Guess I'll have to solve the problem in some other way.
Or you could just describe your problem in a more informative way than "it doesn't work" (without any information of what "it" even is).
did you do like what cubbi said?
yes
Topic archived. No new replies allowed.