There are some misconceptions in your code, which probably comes from your knowledge about arrays. The container std::vector
grows and decreases dynamically, unlike arrays, that have a fixed size and the storage space for each element already exists. With std::vector
, the storage space of the elements is allocated as elements are inserted. Therefore, you cannot access an element without it existing in an object std::vector
. For example, the Code below shows this misconception:
std::vector<int> v;
v[0] = 42; // errado
If v
were just one array of the kind int[N]
, there would be no problem in accessing element 0 (of course, assuming that 0 < N
). Like v
is an object of the type std::vector<int>
, that was initialized by default (default initialization in English), so it contains no elements, that is, it is emptiness.
In order to access an element, we need to enter it first. As you have already discovered, the member function std::vector::push_back
does just that: inserts an element at the end of the vector, correctly allocating enough space for the new element. There is also the member function std::vector::emplace_back
(since c++11), which inserts a new element by passing the arguments passed to it to the element type constructor. Anyway, the example code piece above would be correct as follows:
std::vector<int> v;
v.push_back(42); // ok
int i = v[0]; // também ok: elemento na posição 0 existe.
I’m not sure I understood your intent in your code, but I believe this would fix:
for (int i = 0; i < n; ++i) {
cin >> x;
info.push_back(dados{0, x});
}
If we add a constructor in dados
that starts its members, we can take advantage of the function emplace_back
(for she builds the element in place by calling the builder):
struct dados {
int pessoas;
int consumo;
dados(int pessoas, int consumo)
: pessoas(pessoas)
, consumo(consumo) {}
};
// ...
for (int i = 0; i < n; ++i) {
cin >> x;
info.emplace_back(0, x); // passa-se apenas os argumentos pra construir o novo elemento.
}
The field
consumo
is the typeint
. What would that method bepush_back
?– Woss
As already said by @Andersoncarloswoss, you are making trouble with the fields. The
push_back
can’t be done on aint
how it is doing but yes on thevector
which is yourinfo
– Isac
then I should do something like info[i]. consumption = x ?
– victor