如何使用 stl::map 作为二维数组

发布于 2024-09-12 05:16:40 字数 101 浏览 0 评论 0原文

您能告诉我们如何使用 stl:map 作为二维数组吗?我想访问像 mymap[i][j] 这样的各个元素,但我事先不知道 i 或 j 的值可能是什么。有更好的想法以其他方式做同样的事情吗?

Could you let us know how to use stl:map as two dimension array? I wanted to access the individual elements as like mymap[i][j] where I do not know beforehand what the value of i or j could be. Any better ideas to do the same thing in other way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

贱贱哒 2024-09-19 05:16:40

您可以执行

std::map<int, std::map<int, int> > mymap;

例如,

#include <map>
#include <iostream>

int main() 
{
    std::map<int, std::map<int, int> > mymap;

    mymap[9][2] = 7;
    std::cout << mymap[9][2] << std::endl;

    if (mymap.find(9) != mymap.end() && mymap[9].find(2) != mymap[9].end()) {
        std::cout << "My map contains a value for [9][2]" << std::endl;
    } else {
        std::cout << "My map does not contain a value for [9][2]" << std::endl;
    }

    return 0;
}

以下操作:在标准输出上打印 7,然后是“我的地图包含 [9][2] 的值”。

You can do

std::map<int, std::map<int, int> > mymap;

For example:

#include <map>
#include <iostream>

int main() 
{
    std::map<int, std::map<int, int> > mymap;

    mymap[9][2] = 7;
    std::cout << mymap[9][2] << std::endl;

    if (mymap.find(9) != mymap.end() && mymap[9].find(2) != mymap[9].end()) {
        std::cout << "My map contains a value for [9][2]" << std::endl;
    } else {
        std::cout << "My map does not contain a value for [9][2]" << std::endl;
    }

    return 0;
}

prints 7 on the standard output, followed by "My map contains a value for [9][2]".

眼眸印温柔 2024-09-19 05:16:40

Andrew Stein 的另一种解决方案与 STL 的其余部分配合得更好,就是简单地使用

typedef std::map<std::pair<int, int>, int > AMapT;
AMapT mymap;
mymap[std::make_pair(2, 4)] = 10;
...
AMapT::iterator f = mymap.find(std::make_pair(3, 5));

例如,通过这种方式,您不需要链接两个对 map::find 的调用来搜索单个价值。

An alternative solution to Andrew Stein's which plays nicer with the rest of STL is to simply use

typedef std::map<std::pair<int, int>, int > AMapT;
AMapT mymap;
mymap[std::make_pair(2, 4)] = 10;
...
AMapT::iterator f = mymap.find(std::make_pair(3, 5));

For example, with this way you don't need to chain two calls to map::find to search for a single value.

拔了角的鹿 2024-09-19 05:16:40

考虑使用 kd 树代替。每个级别的分支都会依次比较 i 和 j 的值。请参阅http://en.wikipedia.org/wiki/Kd-tree

Consider using a kd-tree instead. Each level of branching will compare the i an j values in turn. See http://en.wikipedia.org/wiki/Kd-tree.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文