How to use the C++ vector class?

Asked

Viewed 14,329 times

5

Necessarily need the library #include<vector.h>

To raise it

vector <int> c;

Question: How to store values in it and read them?

  • I don’t know much about the language, but take a look here: https://pt.wikibooks.org/wiki/Programar_em_C%2B%2B/Vectors

  • Please do not take this comment lightly, but when someone who is still learning how to use an X resource starts a question with "I necessarily need X", I see a beautiful start of dogma there. Beware, okay? Vectors have their utilities, but they’re not the only and/or best data structure for any and all situations.

3 answers

8


5

As described in the documentation http://www.cplusplus.com/reference/vector/vector/

to put values inside the vector you must use push_back(value) and to take 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
  • 1

    The site cplusplus.com is not considered a good reference. http://stackoverflow.com/questions/6520052/whats-wrong-with-cplusplus-com

3

It’s not very secret, you use push_back to add values, then you can catch them using Dice 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 on https://ideone.com/LllvB0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.