Answers for "Insert into vector C++"

C++
6

insert at position in vector c++

// where v is the vector to insert, i is
// the position, and value is the value

v.insert(v.begin() + i, v2[i])
Posted by: Guest on February-20-2020
14

how to create a vector in c++

// CPP program to create an empty vector 
// and push values one by one. 
#include <vector>

using namespace std;
int main() 
{ 
    // Create an empty vector 
    vector<int> vect;  
    //add/push an integer to the end of the vector
    vect.push_back(10); 
	//to traverse and print the vector from start to finish
    for (int x : vect) 
        cout << x << " ";

    return 0; 
}
Posted by: Guest on April-05-2020
10

adding element in vector c++

vector_name.push_back(element_to_be_added);
Posted by: Guest on April-26-2020
3

add to vector c++

// vector::push_back
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  int myint;

  std::cout << "Please enter some integers (enter 0 to end):\n";

  do {
    std::cin >> myint;
    myvector.push_back (myint);
  } while (myint);

  std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";

  return 0;
}
Posted by: Guest on November-19-2020
2

Insert into vector C++

// inserting into a vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (3,100);
  std::vector<int>::iterator it;

  it = myvector.begin();
  it = myvector.insert ( it , 200 );

  myvector.insert (it,2,300);

  // "it" no longer valid, get a new one:
  it = myvector.begin();

  std::vector<int> anothervector (2,400);
  myvector.insert (it+2,anothervector.begin(),anothervector.end());

  int myarray [] = { 501,502,503 };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
Posted by: Guest on April-03-2020
0

insert vector

#include <iostream>
#include <vector>
 
void print_vec(const std::vector<int>& vec)
{
    for (auto x: vec) {
         std::cout << ' ' << x;
    }
    std::cout << '\n';
}
 
int main ()
{
    std::vector<int> vec(3,100);
    print_vec(vec);
 
    auto it = vec.begin();
    it = vec.insert(it, 200);
    print_vec(vec);
 
    vec.insert(it,2,300);
    print_vec(vec);
 
    // "it" no longer valid, get a new one:
    it = vec.begin();
 
    std::vector<int> vec2(2,400);
    vec.insert(it+2, vec2.begin(), vec2.end());
    print_vec(vec);
 
    int arr[] = { 501,502,503 };
    vec.insert(vec.begin(), arr, arr+3);
    print_vec(vec);
}
Posted by: Guest on July-16-2021

Browse Popular Code Answers by Language