Pushing back an object in a vector without the object - c++

I know that the correct way of push back an object in a vector is to declare an object of the same class and pass it by value as argument of method push_back. i.e. something like
class MyClass{
int a;
int b;
int c;
};
int main(){
std::vector<MyClass> myvector;
MyClass myobject;
myobject.a = 1;
myobject.b = 2;
myobject.c = 3;
myvector.push_back(myobject);
return 0;
}
My question is: it's possible to push back an object passing only the values of the object and not another object? i.e. something like
class MyClass{
int a;
int b;
int c;
};
int main(){
std::vector<MyClass> myvector;
int a = 1;
int b = 2;
int c = 3;
myvector.push_back({a, b, c});
return 0;
}

If you declare a, b, c as public,
class MyClass{
public:
int a;
int b;
int c;
};
then you could use list initialization:
myvector.push_back({a, b, c});
But it could be better to make a constructor
MyClass::MyClass(int a, int b, int c):
a(a), b(b), c(c)
{}
and then use vector::emplace_back
myvector.emplace_back(a, b, c);

To make it work you need at least a C++11 compiler and you need to make a constructor:
class MyClass {
int a;
int b;
int c;
public:
MyClass(int a_, int b_, int c_) : a(a_), b(b_), c(c_) {}
};
You could also make a, b and c public, but I'm guessing you don't want to do that, as it changes the interface of the class.
In response to your question "why is emplace_back better or more efficient than push_back":
By design, emplace_back() should avoid creating a temporary object and should construct "in place" at the end of the vector. With push_back({a, b, c}) you create a temporary MyClass object, which is then copied to the end of the vector. Of course, compiler optimizations may actually lead to same code being generated in both cases, but, by default, emplace_back() should be more efficient. This is further discussed here: push_back vs emplace_back .

Related

Initialize parameter into constructor, other than the first one

I want to explicitly change the second parameter in a constructor of a struct, in the following scenario. Is it possible, if so, how?
struct foo{
int x;
int y;
foo(int a=4, int b=6){
x=a;
y=b;
}
};
int main(){
foo *f = new foo();
cout<<f->x<<" "<<f->y<<endl;
//4 6
foo *g = new foo(3,4);
cout<<g->x<<" "<<g->y<<endl;
//3 4
foo *h = new foo(3);
cout<<h->x<<" "<<h->y<<endl;
//3 6
//Can something like this be
//done in C++, if I want
//to change the value of the
//second variable only
foo *k = new foo(b = 13);
return 0;
}
Is it possible, if so, how?
It is not possible with constructor. In general, c++ does not support named keyword arguments to functions, and it is not possible to skip arguments even if they have a default, if you want to pass a non-default after it.
It will be possible without constructor using list initialisation syntax since C++20 using designated initialisers, if you use default member initialisers:
struct foo{
int x = 4;
int y = 6;
};
int main(){
foo f {.y = 4};
}
You can achieve something similar with tag dispatching; No need for future standard:
struct foo{
int x = 4;
int y = 6;
enum Xtag { Xinit };
enum Ytag { Yinit };
foo(int a, int b) : x(a), y(b) {}
foo(Xtag, int a) : x(a) {}
foo(Ytag, int b) : y(b) {}
};
int main(){
foo f(foo::Yinit, 4);
}
A solution using lambda that can be used without modifying an existing class. Following works with your definition of foo:
auto make_foo_x4 = [](int b) {
return foo(4, b);
};
foo f = make_foo_y(4);
The downside is that we have to explicitly repeat the default value of x, so this can break assumptions if the default is changed in class definition.

How to copy members with same names in different Structures?

I have two different structures. Both have some members of same type & name.
How can I copy all those matching members all at once?
struct a{ int i, int j};
struct b{ int j, int k};
I wanna perform a=b, kind of operation, where b.j get copied into a.j.
Like wise, how any such matching members should get copied?
Just make an assignment operator, and copy everything you want there
struct a{ int i; int j; };
struct b{
void operator=(const a & other)
{
j = other.j;
}
int j;
int k;
};
Then you can just write
a one;
b two;
two = one;
Since there is some set of matching members of the same type maybe the solution is to pack them together to common type.
struct c{ int i, int j};
struct a{ c common, int k, int l, ..., double u};
struct b{ c common, int a, int b, ..., float u, int v};
a one;
b two;
one.common = two.common;
If it is impossible because you cannot change the code this way, then I would suggest to write some copy function, but not assignment operator because some time later you or someone else may and probably will use that assignment incorrectly, thinking that it copies all members.
void copySharedMembersOfAB( a&, a const& b)
{
a.i = b.i;
a.j = b.j;
}

What is wrong with this simple code with vectors?

The following code is one that I written for myself in order to test how pointers and vectors work.
I am very new to C++.
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
//Create the integer pointer vector, and clean it to initialize
vector<int *> lol;
lol.clear();
//Create the pointers and point them to 1,2,3
int a1=1, a2=2, a3=3;
int* a, b, c;
a=&a1;
b=&a2;
c=&a3;
//Put the pointers into the vector
lol.push_back(a);
lol.push_back(b);
lol.push_back(c);
//Return the value of the middle pointer
cout << *lol[1];
}
I get a whole wall of errors while compiling.
Can anyone help? Bear in mind I can only understand novice.
The problem is with this line:
int* a, b, c;
a is int*, but b and c are just ints.
int *a, *b, *c;
Would make it all int*s.
int* a;
int* b
int* c;
does the same thing, but with clearer intentions of declaring three int*s.
See: Placement of the asterisk in pointer declarations
UPDATE: Even better:
int* a = &a1;
int* b = &a2;
int* c = &a3;
Whenever you can, don't separate variable initialization and its declaration.
When declaring multiple pointers on one line, you have to specify the * symbol in front of each pointer variable.
int * a, b, c;
should be :
int *a, *b, *c;
The line :
int * a, b, c;
is interpreted as :
int *a;
int b;
int c;
If you declare variables, do not declare multiple variables on the same line.
What you thought you did was to declare three pointers to int. What you did, was to declare three ints, one of them a pointer:
int* a, b, c;
means
int *a; int b; int c;
Think of the * as belonging to the variable name. Unintuitive, but that's the way the language works.
You want to declare all of the three as pointers:
int* a;
int* b;
int* c;
Change this
int* a, b, c;
to
int *a, *b, *c;
In your declaration you are declaring
a as pointer to int
b as int
c as int
The main problem, as others already noted, are the definitions here:
int* a, b, c;
Basically, only a is an int *; b and c are just ints.
It's just better to have one variable definition per line:
int* a = &a1;
int* b = &a2;
int* c = &a3;
If you use these raw pointers, and if for some reason you want to first define them and then assign their values later, consider at least initializing them to nullptr (or NULL if you are using C++98/03):
// Initialize to NULL/nullptr, to avoid pointers pointing to junk memory
int* a = nullptr;
int* b = nullptr;
int* c = nullptr;
....
// assign proper values to pointers...
Moreover, there are also other notes that can be made for your code:
int main(void)
Since this is C++ - not C - you can omit the (void), and just use () instead:
int main()
When you create the vector:
vector<int *> lol;
lol.clear();
you don't need to call its clear() method after the vector definition: in fact, vector's default constructor (implicitly called by the compiler when you defined the vector in the first line) has already initialized the vector to be an empty vector.
This is just fine:
vector<int *> lol; // Creates an empty vector
Considering these notes, your code can be written something like this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int *> lol;
int a1 = 1;
int a2 = 2;
int a3 = 3;
int * a = &a1;
int * b = &a2;
int * c = &a3;
lol.push_back(a);
lol.push_back(b);
lol.push_back(c);
cout << *lol[1] << endl;
}
First problem is at declaration of pointers
int* a, b, c;
This will create a as pointer and b & c as int.
Use declaration like
int* a,*b,*c;
And While accessing the elements of vector use .at() method of vector.
cout << *lol.at(0) << endl;

C++ constant structure initialization inside a class

How should I write a constructor for a class to initialize a member that is a const structure / has const fields?
In the following example, I define a constructor within structure B and it works fine to initialize it's const fields.
But when I try to use the same technique to initialize const fields of structure C within class A it doesn't work. Can someone please help me and rewrite my class A in a way, that it starts working?
#include <iostream>
class A
{
public:
struct C
{
C (const int _x) : x (_x) {}
const int x;
};
C c (3);
};
int main (int argc, char *argv[])
{
struct B
{
B (const int _x) : x (_x) {}
const int x;
};
B b (2);
std::cout << b.x << std::endl;
A a;
std::cout << a.c.x << std::endl;
return 0;
}
P.S.
I did some search and I think, I understand, that unless I have C++11 support or want to use boost library, I have to define a helper function to initialize a const struct within initialization list
(C++ Constant structure member initialization)
but it seems to be crazy that I have to define alike struct, but with non const fields to initialize a struct with const fields, doesn't it?
Another thing that I found tells that I should initialize const members in a constructor of the class A, rather than in a constructor of the struct C (C++ compile time error: expected identifier before numeric constant) but it also seems crazy to me, because why should I rewrite a class constructor every time I want to add a new struct, isn't it more convenient to have a separate constructor for each struct C within the class A?
I would be grateful to any comments that could possibly clarify my confusion.
I'd do the job like this:
#include <iostream>
class A {
public:
struct C {
C(const int _x) : x(_x) {}
const int x;
};
C c; // (3);
A() : c(3) {}
};
int main(int argc, char *argv []) {
A a;
std::cout << a.c.x << std::endl;
return 0;
}
Note that it's not a matter of using a ctor in A or in C, but of the ctor for A telling how the ctor for C should be invoked. If the value that will be passed will always be 3 that's not necessary, but I'm assuming you want to be a able to pass a value of your choice when you create the C object, and it will remain constant after that.
If the value will always be the same (3 in this case) you can simplify things a lot by also making the constant static:
struct A {
struct C {
static const int x = 3;
};
C c;
};
int main() {
A a;
std::cout << a.c.x << "\n";
}
So, if the value is identical for all instances of that class, make it static const, initialize it in place, and life is good. If the value is not known until you create an instance of the object, and remains constant thereafter for the life of that object, you need to pass it in through the constructors.
For a slightly different case, there's a third possibility: if C is an independent class (not nested inside of A) you might have a situation where other instances of C use various values, but all instances of C inside an A always use the same value. In this case, you'd do something like:
struct C {
const int x;
C(int x) : x(x) {}
};
struct A {
C c;
A() : c(3) {}
};
Of course, you can do the same thing when C is nested inside of A, but when/if you do, it generally means you're setting the same value for all instances of C, so you might as well use the static const approach instead. The obvious exception would be if A had multiple constructors, so (for example) A's default constructor passed one value for C::x and its copy constructor passed a different value.

Temporaries created during assignment operation

if every assignment creates a temporary to copy the object into lvalue, how can you check to see in VC++ 8.0?
class E
{
int i, j;
public:
E():i(0), j(0){}
E(int I, int J):i(I), j(J){}
};
int main()
{
E a;
E b(1, 2);
a = b //would there be created two copies of b?
}
Edit:
Case 2:
class A
{
int i, j;
public:
A():i(0), j(0){}
};
class E
{
int i, j;
A a;
public:
E():i(0), j(0){}
E(int I, int J):i(I), j(J){}
E(const E &temp)
{
a = temp; //temporary copy made?
}
};
int main()
{
E a;
E b(1, 2);
a = b //would there be created two copies of b?
}
From your comment, you made it clear that you didn't quite understand this C++-FAQ item.
First of all, there are no temporaries in the code you presented. The compiler declared A::operator= is called, and you simply end up with 1 in a.i and 2 in a.j.
Now, regarding the link you provided, it has to do with constructors only. In the following code :
class A
{
public:
A()
{
s = "foo";
}
private:
std::string s;
};
The data member s is constructed using std::string parameterless constructor, then is assigned the value "foo" in A constructor body. It's preferable (and as a matter of fact necessary in some cases) to initialize data members in an initialization list, just like you did with i and j :
A() : s("foo")
{
}
Here, the s data member is initialized in one step : by calling the appropriate constructor.
There are a few standard methods that are created automatically for you if you don't provide them. If you write
struct Foo
{
int i, j;
Foo(int i, int j) : i(i), j(j) {}
};
the compiler completes that to
struct Foo
{
int i, j;
Foo(int i, int j) : i(i), j(j)
{
}
Foo(const Foo& other) : i(other.i), j(other.j)
{
}
Foo& operator=(const Foo& other)
{
i = other.i; j = other.j;
return *this;
}
};
In other words you will normally get a copy constructor and an assignment operator that work on an member-by-member basis. In the specific the assignment operator doesn't build any temporary object.
It's very important to understand how those implicitly defined method works because most of the time they're exact the right thing you need, but sometimes they're completely wrong (for example if your members are pointers often a member-by-member copy or assignment is not the correct way to handle the operation).
This would create a temporary:
E makeE( int i, int j )
{
return E(i, j);
}
int main()
{
E a;
a = makeE( 1, 2 );
E b = makeE( 3, 4 );
}
makeE returns a temporary. a is assigned to the temporary and the assignment operator is always called here. b is not "assigned to", as it is being initialised here, and requires an accessible copy-constructor for that to work although it is not guaranteed that the copy-constructor will actually be called as the compiler might optimise it away.