gpt4 book ai didi

C++0x 3d map 像在 php 关联数组中一样初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:29 24 4
gpt4 key购买 nike

我刚刚进入新的 c++0x 东西并实例化这样的 map :

std::map<int, std::map<int, int>> foo;
foo[1][2] = 3;

很容易实现。但是我可以在 php 中做一些类似的事情吗?

$array = array(
1 => array(
2 => array(
3
)
)
);

我不熟悉语法。也许是这样的

foo[][][] = {
1 {
2 {3}
}
};

所以我不必一直写索引:

foo[1][2] = 3;
foo[1][3] = 4;
foo[1][4] = 5;

最佳答案

是的,使用 c++11 特性统一初始化:

#include <iostream>
#include <map>

int main()
{
// The value_type of a map is pair<const Key, T>.
// To initialize a map an initializer list
// of pair<Key, T> objects must be specified.

// To initialize a pair:
//
std::pair<int, int> p{9, 10};
std::cout << "pair:\n (" << p.first << ", " << p.second << ")\n\n";

// To initialize a simple map (no nesting)
// with value_type of pair<int, int>:
//
std::map<int, int> simple_map
{ // K V
{ 5, 6 },
{ 7, 8 }
};
std::cout << "simple_map:\n";
for (auto const& i: simple_map)
{
std::cout << " (" << i.first << ", " << i.second << ")\n";
}
std::cout << "\n";

// To initialize a complex map (with nesting)
// with value_type of pair<const int, map<int, int>>
//
const std::map<int, std::map<int, int>> complex_map
{ // K V
// k v
{ 1, { {3, 4},
{5, 6} }
},
{ 2, { {7, 8},
{8, 8},
{9, 0} }
}
};

std::cout << "complex_map:\n";
for (auto const& mi: complex_map)
{
std::cout << " (" << mi.first << ", ";
for (auto const& p: mi.second)
{
std::cout << '(' << p.first << ", " << p.second << ')';
}
std::cout << ")\n";
}
}

输出:

pair:  (9, 10)simple_map:  (5, 6)  (7, 8)complex_map:  (1, (3, 4)(5, 6))  (2, (7, 8)(8, 8)(9, 0))

查看在线演示 http://ideone.com/hCjtjP .

关于C++0x 3d map 像在 php 关联数组中一样初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16701122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com