2014-03-03 59 views
0

我是C++映射的新手。我想在我的程序中使用类似以下的地图。在C++中使用映射<pair <int,int>,string>

std::map<std::pair<int,int>,string> pattern 

这里的关键int,int实际上行的二维网格的位置和列位置和列是未知的最初。所以我曾经想过最初将列设置为0.在程序过程中,它也可能是负面的。那么任何人都可以帮助我如何访问和设置这样的地图的元素?

+2

您是不是要找'的std ::地图<性病::对,字符串> pattern'? – Brian

+0

绝对是。 – Joy

+2

究竟是什么问题? “map”类的文档在设置/检索元素方面非常清晰和简洁。 http://en.cppreference.com/w/cpp/container/map – Jack

回答

1

你的问题并不完全清楚。但是这个小示例演示了如何初始化其关键字由行列对组成的映射(本例中为10行和10列),每个键的值都是“行,列”模式。然后样本迭代地图并打印出地图的每个键值对。

map<pair<int,int>,string> patterns; 

for (int i = 0; i < 10; i++) { 
    for (int j = 0; j < 10; j++) { 
     patterns[make_pair(i, j)] = std::to_string (i) + ", " + std::to_string (j); 
    } 
} 

for (const auto &pair : patterns) { 
    std::cout << pair.first.first << "," << pair.first.second << ": " << pair.second << '\n'; 
    //note pair.first in the row column pair, pair.first.first is the row, pair.first.second is the column, pair.second is the string pattern 
} 
0

只要你编译C++ 11模式(其如在2014年,你应该),该对中的值可以被指定为一个支撑-INIT列表,例如{ 4, -13 },在map的大部分界面功能中。这不适用于emplace或使用完美转发的其他任何内容。

例如:

patterns[{ 1, 2 }] = "hello"; // set a given element 
patterns.at[{ 1, 2 }] = "Hello"; // alter a given pre-existing element 
foo(patterns.at[{ 1, 2 }]); // pass a (reference to) pre-existing element 
patterns.erase({ 3 , 4 }); // ensure that given element no longer exists 
相关问题