I am trying to create a queue of 2d points, like this:
queue<int[2]> q;
this compiles, however, after doing:
q.push({0,0});
I get an compile error, saying that my call to push
is ambiguous. Not sure how to fix this. Please help.
I'm not sure if this is a good way to represent 2d points on a plane, but it seems to me to be the most lightweight.
CodePudding user response:
You can create a structure for the 2D points:
struct Point2D {
int x;
int y;
};
And you can create a std::vector
instead of std::queue
.
std::vector<Point2D> q {{ {1, 2}, {9, 3}, ... }};
And you can normally:
q.push_back({0, 0});
EDIT:
You can also create a vector of int[2]
instead of Point2D
and do the same thing.
CodePudding user response:
You can always create a struct to hold your point coordinates. It's actually a good idea to have a representation for such entity regardless of your current problem.
The answer below is a more general one regarding arrays in c , and does not require a custom struct:
In c it's usually recomended to use std::array
instead of such small fixed size c style arrays (and std::vector
for dynamic size ones).
Code example:
#include <queue>
#include <array>
int main() {
std::queue<std::array<int,2>> q;
q.push({ 0,0 });
return 0;
}
A side note: better to avoid using namespace std
- see here Why is "using namespace std;" considered bad practice?.
CodePudding user response:
You can use Pair to represent your points.
queue<pair<int,int>>q;
q.push({0,0});
CodePudding user response:
Array are just pointers. Raw C arrays cannot be stored in container.
Solution 1: Use type of stored element as int*
std::queue<int*> q1;
int s1[2]{0,0};
q1.push(s1);
Solution 2: Use other container like std::array or std::vector
std::queue<std::array<int,2>> q;
q.push({0,0});