How to create new vector with pointer in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

template<typename T>
void printVector(std::vector<T> *p) {
    for (auto i = 0; i < p->size(); i++) {
        std::cout << p->at(i) << " ";
    }
    std::cout << "\n";
}

int main() {
    auto *p = new std::vector<int>(5);
    
    printVector(p);
    
    for (int i = 0; i < 5; i++) {
        p->at(i) = i + 1;
        std::cout << p->at(i) << " ";
    }
}




/*
run:

0 0 0 0 0 
1 2 3 4 5 

*/

 



answered May 13, 2021 by avibootz
...