ManmeetP
0
Q:

c++ resize vector with value

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed.

If n is greater than current container size then new elements are inserted at the end of vector.

If val is specified then new elements are initialed with val.
4
// resizing of the vector 
#include <iostream> 
#include <vector> 
  
using namespace std; 
  
int main() 
{ 
    vector<int> vec; 
  
    // 5 elements are inserted  
    // in the vector 
    vec.push_back(1); 
    vec.push_back(2); 
    vec.push_back(3); 
    vec.push_back(4); 
    vec.push_back(5); 
  
    cout << "Contents of vector before resizing:" 
         << endl; 
      
    // displaying the contents of the 
    // vector before resizing 
    for (int i = 0; i < vec.size(); i++) 
        cout << vec[i] << " "; 
  
    cout << endl; 
  
    // vector is resized 
    vec.resize(8); 
  
    cout << "Contents of vector after resizing:" 
         << endl; 
  
    // displaying the contents of  
    // the vector after resizing 
    for (int i = 0; i < vec.size(); i++) 
        cout << vec[i] << " "; 
  
    return 0; 
} 
2
// resizing of the vector 
#include <iostream> 
#include <vector> 
  
using namespace std; 
  
int main() 
{ 
    vector<int> vec; 
  
    // 5 elements are inserted 
    // in the vector 
    vec.push_back(1); 
    vec.push_back(2); 
    vec.push_back(3); 
    vec.push_back(4); 
    vec.push_back(5); 
  
    cout << "Contents of vector before resizing:" 
         << endl; 
      
    // displaying the contents of the 
    // vector before resizing 
    for (int i = 0; i < vec.size(); i++) 
        cout << vec[i] << " "; 
  
    cout << endl; 
  
    // vector is resized 
    vec.resize(4); 
  
    cout << "Contents of vector after resizing:" 
         << endl; 
      
    // displaying the contents of the 
    // vector after resizing 
    for (int i = 0; i < vec.size(); i++) 
        cout << vec[i] << " "; 
  
    return 0; 
} 
0

New to Communities?

Join the community