could someone please explain why this code produces. i was able to narrow the error to this segment regardless of what I set the map value to.
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\include\xstddef(117,1): error C2784: 'bool std::operator <(std::nullptr_t,const std::shared_ptr<_Ty> &) noexcept': could not deduce template argument for 'const std::shared_ptr<_Ty> &' from 'const _Ty'
struct Vector2i
{
int x;
int y;
};
std::map<Vector2i, Chunk*> map{};
map.insert({ Vector2i{0,0}, nullptr });
thanks :)
I tried commenting out all other instances of the Vector2i struct and this segment seemed to be the only place that causes this error.
CodePudding user response:
The std::map is an ordered container, and therefore requires keys to provide a "less-than" operator for comparison. This can be provided in the map's template arguments, or it can be implicit if you have defined operator<
for your type.
struct Vector2i
{
int x;
int y;
bool operator<(const Vector2i& other) const {
return x < other.x || x == other.x && y < other.y;
}
};
CodePudding user response:
You should provide comparison operator to your map. Here is some ways.
Define operator< inside struct.
struct Vector2i
{
...
bool operator<(const Vector2i& rhs) const {
return x < rhs.x;
}
};
Define outside the struct.
bool operator< (const Vector2i& lhs, const Vector2i& rhs) {
return lhs.x < rhs.x;
}
Define struct comparator and pass to constructor of map.
struct cmpByStringLength {
bool operator()(const Vector2i& lhs, const Vector2i& rhs) const {
return lhs.x < rhs.x;
}
};
std::map<Vector2i, Chunk*, cmpByStringLength> mp{};
Using lambda function.
auto comp = [](const Vector2i& a, const Vector2i& b) { return a.x < b.x; };
std::map<Vector2i, Chunk*, decltype(comp)> mp{};