How do I add a value to a struct vector, for example in some vector field, since it is from a struct

2
#include <iostream>
#include <vector>
using namespace std;


struct dados {
    int pessoas;
    int consumo;
};

int main()
{



    int totalx=0, totaly=0;
    int n,x,y;
     vector<dados> info;
    //int cidade = 1;
    cout << "Insira valor para N: ";
    cin >> n;

    for(int i = 0; i < n; i++){
        cin>> x;
        info[i].consumo.push_back(x); // como  add um valor para o campo do vector, pois ele é do tipo 'dados',uma struct ? 
    }





return 0;
}
    
asked by anonymous 01.05.2018 / 17:43

1 answer

2

There are some misconceptions in your code, which probably comes from your knowledge of arrays . The std::vector container grows and decreases dynamically, unlike arrays, which 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 entered. Therefore, you can not access an element without it in a std::vector object. For example, the code below shows this misconception :

std::vector<int> v;
v[0] = 42; // errado

If v was just an array of type int[N] , there would be no problem accessing element 0 (of course, assuming 0 < N ). As v is an object of type std::vector<int> , which was initialized by default ( default initialization in English), so it does not contain elements, ie empty .

In order to access some element, we must first insert it. As you may have already discovered, the member function std::vector::push_back does just that: inserts an element at the end of the array, properly allocating enough space for the new element. There is also the member function std::vector::emplace_back (since ), which inserts a new element passing the arguments passed to it to the constructor of the element type. Anyway, the above example piece of code would look like this:

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 think it 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 emplace_back function (since it constructs the element in place by calling the constructor):

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.
}
    
02.05.2018 / 06:01