【问题标题】:Assign to an ID more elements将更多元素分配给一个 ID
【发布时间】:2020-06-10 08:22:36
【问题描述】:

我是 C++ 新手。我需要迭代地分配给一个渐进式 ID (int)、3 个坐标 (int)。 例如,如果我的 ID=3,我分配给它坐标={2,4,6}。 C++ 中有一个结构可以做到吗?

谢谢

【问题讨论】:

标签: c++ arrays vector iteration coordinates


【解决方案1】:

您可以创建一个std::map,它将一个整数(您的渐进式 ID)“映射”到一个 3 元组(因为您只需要 3 个坐标)。

你可以这样做:

map<int, tuple<int, int, int> > my_map; // id, coordinates

确保#include &lt;map&gt;#include &lt;tuple&gt;std::mapstd::tuple 的定义所必需的。

一个关于如何使用它的例子:

map<int, tuple<int, int, int> > my_map;
int id = 27;
auto coord = make_tuple(3, 4, 5);
my_map[id] = coord;

cout << "ID: 27, coordinates: " << get<0>(my_map[id]) << get<1>(my_map[id])
                                << get<2>(my_map[id]); //prints 345

【讨论】:

    【解决方案2】:

    如果您熟悉它,您可以使用 stl 中提供的地图或 unordered_map。只需检查一下,它们的实现非常简单。

    使用

    map<int,vector<int>> m;
    

    unordered_map<int,vector<int>> um;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多