How to push_back a vector <struct> ?

Let's say I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <vector>
using namespace std;

struct something {
    int x;
    double y;
    char c;
};

int main() {
	vector <something> v (1);
	cin >> v[0].x >> v[0].y >> v[0].c;
}


I would like to store the same struct with different values inside the vector however I cannot do it since it's full so I have to use v.push_back() however I have no idea how to use it when dealing with structs.
Last edited on
You could look at vector::emplace_back (and provide a constructor for something), but also reorder your logic. First make one something, then add it to the vector.
you could use emplace_back to construct something objects directly within the container (here std::vector<something>) provided corresponding ctor overloads:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

struct something {
    int m_x;
    double m_y;
    char m_c;
    something(const int x, const double y, const char c)
        : m_x(x), m_y(y), m_c(c){}
};

int main()
{
	std::vector <something> v {};
	//say you want 5 something objects in the vector
	for (auto i = 0; i < 5; ++i)
    {
        std::cout << "enter int \n"; int x{}; std::cin >> x;
        std::cout << "enter double \n"; double y{}; std::cin >> y;
        std::cout << "enter char \n"; char c{}; std::cin >> c;
        v.emplace_back((something(x, y, c)));
    }
	for (const auto& elem : v)
    {
        std::cout << elem.m_x << " " << elem.m_y << " " << elem.m_c << "\n";
    }
}

http://stackoverflow.com/questions/23717151/why-emplace-back-is-faster-than-push-back
First make one something, then add it to the vector.

keskiverto – with emplace_back, wouldn't it be better to construct the something objects directly into the container?
I would like to avoid using emplace_back since it was implemented in C++11. I am coding in raw C++.

So what are my options? I can only think of this as keskiverto said:
First make one something, then add it to the vector.


1
2
3
	something s;
	cin >> s.x >> s.y >> s.c;
	v.push_back(s);


Doing it this way, you can add endless structs to the vector with a simple loop
Last edited on
Topic archived. No new replies allowed.