How to use the vector class of C ++?

3

Needs the library #include<vector.h>

To create it

vector <int> c;

Question: How do I store values in it and read them?

    
asked by anonymous 15.03.2016 / 18:32

3 answers

5

For these things, it's always interesting to check quasi-official documentation and ask more specific questions of what you did not understand with a real example of what you are doing.

One of many ways would be:

vector <int> c { 1, 2, 3 }; //inicializa
c.push_back(4); //adiciona
cout << c[2]; //pega o elemento

Searches and other operations are done in general algorithms for any data collection.

Alternative Documentation .

    
15.03.2016 / 18:55
4

As described in the documentation link

To put values inside the vector you should use push_back (value) and to get a value you can use the [] operator or the at function.

vector <int> c;
c.push_back(3);
c.push_back(4);
int a = c[0] // a recebe o valor 3
int b = c.at(1) // b recebe o valor 4
    
15.03.2016 / 18:53
2

It does not have much secret, you use the push_back to add values, then you can get them using the index or an iterator.

Example:

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

int main(){

    vector<int> vetor;
    int i;

    // INSERINDO 5 VALORES DE 1 A 5  USANDO PUSH_BACK
   for(i = 0; i < 5; i++){
      vetor.push_back(i);
   }
    // PEGANDO O TAMANHO DO VETOR
    cout << "Tamanho do Vetor = " << vetor.size() << endl;

    // ACESSANDO OS 5 VALORES DO VETOR PASSANDO PELO INDEX
    for(i = 0; i < 5; i++){
      cout << "Valor do vetor [" << i << "] = " << vetor[i] << endl;
   }

   // OU USANDO O ITERATOR PARA ACESSAR OS VALORES.
   vector<int>::iterator v = vetor.begin();
   while( v != vetor.end()) {
      cout << "Valor do vetor = " << *v << endl;
      v++;
   }
    return 0;
}

See working at link

    
15.03.2016 / 19:00