I was wondering if it is possible to dynamically allocate a vector using new keyword, similar to an array.
what I mean is this:
vector<int> *vptr = new vector<int>;
I could not find proper reference about this problem over the internet. I would like to know what the below statement means. Both are valid syntax. Also how to dereference the pointer here.
vector<int> *vptr = new vector<int>[10];
vector<int> *vptr1 = new vector<int>(2,5);
CodePudding user response:
First things first, creating std::vector
dynamically(like you do in the example) should not be your first choice.
I would like to know what the below statement means
Let's look at them one by one.
Case 1
Here we consider the statement:
vector<int> *vptr = new vector<int>[10];
This creates 10 empty std::vector<int>
s and initialize the pointer vptr
with the pointer to the very first of those dynamically created vectors. You can compare this with int *ptr = new int[10];
.
Case 2
Here we consider the statment:
vector<int> *vptr1 = new vector<int>(2,5);
This creates a single std::vector<int>
of size 2
with each of its elements initialized to 5
and then the pointer vptr
is initialized with the pointer to that dynamically created vector.
CodePudding user response:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// v is pointer toward a vector<int>
vector<int> *v = new vector<int>();
// So we should use '->' to dereference
// and use the method push_back
v->push_back(1);
v->push_back(2);
v->push_back(3);
for (auto i = 0u; i < v->size(); i ) {
// we are using at method to access
// elements as it is more readable
// than (*v)[i]
cout << v->at(i) << endl;
}
// v1 is an array of vector<int>
vector<int> *v1 = new vector<int>[10];
for (int i = 0; i < 10; i ) {
// we access to the ith vector with
// the [] operator same way we deal
// with other arrays. v[i] is of type
// vector so we use directly the push_back method
v1[i].push_back(i);
}
for (int i = 0; i < 10; i ) {
cout << v1[i][0] << endl;
}
delete [] v1;
// same as v
vector<int> *v2 = new vector<int>(2, 3);
for (auto i = 0u; i < v2->size(); i ) {
cout << v2->at(i) << endl;
}
return 0;
}