#include <iostream>
using namespace std;
#include <vector>
#include <queue>
int main(){
vector<int> *v = new vector<int>;
v -> push_back(1);
//min priority queue
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(v[0]); //Able to do pq.push(v -> at(0))
}
So why is this giving an error? Am i not pushing an integer inside my priority queue?
CodePudding user response:
A std vector already manages its buffer dynamically.
In 99.9% of cases, new std::vector
is a mistake.
vector<int> v;
v . push_back(1);
//min priority queue
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(v[0]);
this works.
If you are really in the 0.1% of cases where new on a vector makes sense, change v[0]
to (*v)[0]
.
What v[0]
does is treat the pointer v
as a pointer to an array of vectors. It then picks the 0th one. It does not pick the 0th element of the 0th one. v[0][0]
would also work, but would be dumb.
So C inherits an array pointer duality from C. When you have a pointer, you can use square brackets to treat it as an array as if it was the pointer to the first element of the array.
C also has objects, and those objects can overload operators like square brackets. The overloading happens on the objects not on pointers to those objects.
So vector[]
fakes being an array and finds the elements owned by the vector. ptr_to_vector[]
insteat treats it as an array of vectors starting at *ptr_to_vector
, almost never what you want.
C is relatively unique in having full fledged objects that can be values. Few languages do. This can be confusing if you are coming from other languages. Embrance value semantics in C when you can.
CodePudding user response:
This will fix your compile
pq.push((*v)[0]);
Since v is pointer to a vector<int>
.
In this case pq.push
will accept only an int as input. v[0]
will return a vector<int>
object. If you really want to use [] index operator you can go with pq.push(v[0][0])
Reworked code:
#include <iostream>
using namespace std;
#include <vector>
#include <queue>
int main(){
vector<int> *v = new vector<int>;
v -> push_back(1);
//min priority queue
priority_queue<int, vector<int>, greater<int>> pq;
pq.push((*v)[0]);
delete v; // don't forget.
}