vendredi 6 novembre 2020

Using push_back vs at in a vector in C++

Have a doubt in using vectors in C++. it is to do with the push_back method in the vector. For the first program, i have used push_back to insert elements into the vector. For the second program, i have used at( ) to insert elements into the vector.

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main ()
{
  std::vector<string> myvector (3);

  cout << "In main" << endl;
  for (unsigned i=0; i<myvector.size(); i++)
  {
    myvector.push_back("hi");  //Note: using push_back here.
  }
  cout << "elements inserted into myvector" << endl;

  std::cout << "myvector contains:" << endl;
  for (auto v: myvector)
     cout << v << endl;

  // access 2nd element
  cout << "second element is " << myvector[1] << endl;

  return 0;
}
Output:    
Hangs after entering main.    
$ ./a.out    
In main

whereas if I used myvector.at() to insert the elements like below, its fine.

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main ()
{
  std::vector<string> myvector (3);

  cout << "In main" << endl;
  for (unsigned i=0; i<myvector.size(); i++)
  {
    myvector.at(i) = "hi";  // using 'at' instead of 'push_back'
  }
  cout << "elements inserted into myvector" << endl;

  std::cout << "myvector contains:" << endl;
  for (auto v: myvector)
     cout << v << endl;

  // access 2nd element
  cout << "second element is " << myvector[1] << endl;

  return 0;
}

Output:
./a.out
In main
elements inserted into myvector
myvector contains:
hi
hi
hi
second element is hi
$

What is wrong with the way i have used push_back ? This is one of the ways we insert elements into the vector, right.

Aucun commentaire:

Enregistrer un commentaire