c++ - 无论如何要将键,值,值存储到 map 中

标签 c++ dictionary containers duplicate-removal

在通读了大部分maps 问题之后,我最终从这个链接中得到了一个想法:How to unique my data that are stored in an object which are stored in a vector?

我的任务是存储来自用户输入的 XYZ 坐标。为了防止用户输入重复数据,我决定使用 map 容器,因为它们不允许重复数据。

我测试了代码。

我使用 X 作为 key 和 Y 作为 value

我可以通过以下方式存储 XY:

map<int, int> mapp2d;
mapp2d.insert(pair<int, int>(X, Y));

并通过此访问它们:

map<int, int>::iterator p = mapp2d.begin();
map<int, int>::iterator e = mapp2d.end();
while ( p != mapp2d.end())
{
    cout << "X: " << p->first << " Y: " << p->second << endl;
    p++; 
}

是否可以为 XYZ 执行此操作?像这样:

map<int, int, int> mapp3d
mapp3d.insert(pair<int, int, int>(X, Y, Z))

我测试了代码,但出现了以下错误:

error: wrong number of template arguments (3, should be 2)
error: provided for ‘template<class _T1, class _T2> struct std::pair

是的,我确实知道我这样做是违法的,但是没有关于我应该如何做的教程,我有点用尽了想法,我该如何访问它们?

感谢你们的关注,提前致谢。

最佳答案

您应该将坐标存储在一起,而不是使用一个坐标作为键:

struct Point
{
    int x, y, z;

    Point(int x, int y, int z) : x(x), y(y), z(z) {}
};

然后只需实现一个自定义比较器:

struct PointComparator
{
    bool operator()(const Point& a, const Point& b)
    {
        if (a.x < b.x) return true;
        if (a.x == b.x && a.y < b.y) return true;
        if (a.x == b.x && a.y == b.y && a.z < b.z) return true;
        return false;
    }
};

最后,使用 set而不是 map (因为在您的情况下,值和键是相同的):

#include <set>
std::set<Point, PointComparator> points;

集合(就像 map )是有序的,默认情况下从低值到高值。您需要在此处指定一个自定义比较器,因为如果您只执行 std::set<Point>,则会使用默认比较器。是std::less .这个比较器可以比较数字等,但不知道如何比较 Point 类型的对象。 .因此,该集合无法正确排序其元素,也无法确定两个元素是否相同(这就是您所追求的)。如果你这样做std::set<Point, PointComparator> ,您创建一个使用 PointComparator 中的逻辑的集合比较其元素。

此示例将打印“1”和“2”:

points.insert(Point(1, 2, 3));
points.insert(Point(1, 2, 3));
points.insert(Point(2, 3, 4));

std::set<Point, PointComparator>::iterator it = points.begin();
while (it != points.end()) {
    std::cout << "x = " << it->x << std::endl;
    it++;
}

关于c++ - 无论如何要将键,值,值存储到 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30424050/

相关文章:

c++ - 最佳容器类型

c++ - 为什么这段 C++ 代码会产生段错误?

C++编程题

python - 如何使用正则表达式从多行字符串中获取groupdict

python - 如何在python中将数据框的列和行添加为字典的键和值

css - 有边界的绝对位置?

c++ - 用户模式下可用的最低级别的 WinSock API 是什么? (用于 API 注入(inject)蹦床。)

c++ - 有没有办法在 C++ 中扩展动态内存数组?

c++ - 在 C++ 中将字符串和列表添加到映射

apache - Docker容器无法启动