How to resize a vector in C++

4 Answers

0 votes
#include <iostream>
#include <vector>
  
void printVector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}

int main()
{
    std::vector<int> v = { 5, 2, 7, 1, 9, 3, 6, 4 };

    v.resize(13);
    
    printVector(v);
 
    return 0;
}
 
   
   
   
   
/*
run:
   
5 2 7 1 9 3 6 4 0 0 0 0 0 
    
*/

 



answered Apr 10, 2020 by avibootz
0 votes
#include <iostream>
#include <vector>
  
void printVector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}

int main()
{
    std::vector<int> v = { 5, 2, 7, 1, 9, 3, 6, 4 };

    v.resize(5);
    
    printVector(v);
 
    return 0;
}
 
   
   
   
   
/*
run:
   
5 2 7 1 9 
    
*/

 



answered Apr 10, 2020 by avibootz
0 votes
#include <iostream>
#include <vector>
  
void printVector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}

int main()
{
    std::vector<int> v = { 5, 2, 7, 1, 9, 3, 6, 4 };

    v.resize(5);
    v.resize(9, 888);
    
    printVector(v);
 
    return 0;
}
 
   
   
   
   
/*
run:
   
5 2 7 1 9 888 888 888 888 
    
*/

 



answered Apr 10, 2020 by avibootz
0 votes
#include <iostream>
#include <vector>
  
void printVector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}

int main()
{
    std::vector<int> v = { 5, 2, 7, 1, 9, 3, 6, 4 };

    v.resize(5);
    v.resize(9, 888);
    v.resize(12, 777);
    v.resize(16);
    
    printVector(v);
 
    return 0;
}
 
   
   
   
   
/*
run:
   
5 2 7 1 9 888 888 888 888 777 777 777 0 0 0 0 
    
*/

 



answered Apr 10, 2020 by avibootz
...