Answers for "vector operations in c++"

C++
31

c++ vector

#include <vector>

int main() {
  std::vector<int> v;
  v.push_back(10); // v = [10];
  v.push_back(20); // v = [10, 20];
  
  v.pop_back(); // v = [10];
  v.push_back(30); // v = [10, 30];
  
  auto it = v.begin();
  int x = *it; // x = 10;
  ++it;
  int y = *it; // y = 30
  ++it;
  bool is_end = it == v.end(); // is_end = true
  
  return 0;
}
Posted by: Guest on March-17-2020
0

vector operations in c++

#include <iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    int n;
    cin>>n;
    vector<int>vec(n);
    for(int i=0;i<n;i++)
    {
        cin>>vec[i];
    }
    cout<<"----------"<<endl;
    for(int i=0;i<n;i++)
    {
      cout<<vec[i]<<" ";
    }
    vec.push_back(100);
    vec.push_back(200);
    cout<<endl;
    auto it=vec.begin();
    vec.insert(it,3,1000);
    for(vector<int>::iterator it1=vec.begin();it1!=vec.end();it1++)
    {
        cout<<*it1<<" ";
    }
    cout<<endl;
    vector<int>vec2;
    vec2.push_back(15);
    vec2.push_back(25);
    vec2.push_back(35);
    vec.insert(it,vec2.begin(),vec2.end());
    for(vector<int>::iterator it1=vec.begin();it1!=vec.end();it1++)
    {
        cout<<*it1<<" ";
    }
    cout<<endl;
    vec.pop_back();
    vec.pop_back();
    for(vector<int>::iterator it1=vec.begin();it1!=vec.end();it1++)
    {
        cout<<*it1<<" ";
    }
    cout<<endl;
    int k;
    cin>>k;
    cout<<endl;
    vector<int>::iterator its=vec.begin()+k-1;
    int s=vec.size();
    cout<<s<<endl;
    vec.erase(its);
    for(vector<int>::iterator it1=vec.begin();it1!=vec.end();it1++)
    {
        cout<<*it1<<" ";
    }
    

    return 0;
}
Posted by: Guest on June-04-2021

Browse Popular Code Answers by Language