初始化静态地图的正确方法是什么?我们需要一个初始化它的静态函数吗?
这是我出来的可能方式之一:
struct RetrieveKey
{
    template <typename T>
    typename T::first_type operator()(T keyValuePair) const
    {
        return keyValuePair.first;
    }
};
map<int, int> m;
vector<int> keys;
// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());
// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));
当然,我们也可以通过定义另一个仿函数RetrieveValues从地图中检索所有值.
有没有其他方法可以轻松实现这一目标?(我总是想知道为什么std :: map不包含我们这样做的成员函数.)
我已经确定了四种不同的插入方式std::map:
std::map<int, int> function;
function[0] = 42;
function.insert(std::map<int, int>::value_type(0, 42));
function.insert(std::pair<int, int>(0, 42));
function.insert(std::make_pair(0, 42));
哪一种是首选/惯用的方式?(还有另一种我没想过的方法吗?)
我想知道,当我将元素插入地图时,建议的方法是什么.我是不是该
map[key] = value;
要么
map.insert(std::pair<key_type, value_type>(key, value));
我做了以下快速测试:
#include <map>
#include <string>
#include <iostream>
class Food {
public:
    Food(const std::string& name) : name(name) { std::cout << "constructor with string parameter" << std::endl; }
    Food(const Food& f) : name(f.name) { std::cout << "copy" << std::endl; }
    Food& operator=(const Food& f) { name = f.name; std::cout << "=" << std::endl; return *this; } 
    Food() { std::cout << "default" << std::endl; }
    std::string name;
};
int main() { …假设您要保留现有条目的地图.20%的情况下,您插入的条目是新数据.使用返回的迭代器执行std :: map :: find然后std :: map :: insert是否有优势?或者是否更快尝试插入然后根据迭代器是否指示记录是否插入来执行操作?
如何std::map在使用该find方法后更新密钥的值?
我有这样的map和iterator声明:
map <char, int> m1;
map <char, int>::iterator m1_it;
typedef pair <char, int> count_pair;
我正在使用地图来存储角色的出现次数.
我正在使用Visual C++ 2010.
我试图弄清楚为什么以下代码不起作用,我假设使用char*作为键类型是一个问题,但是我不知道如何解决它或为什么它发生.我使用的所有其他功能(在HL2 SDK中)使用char*这样std::string会导致很多不必要的复杂化.
std::map<char*, int> g_PlayerNames;
int PlayerManager::CreateFakePlayer()
{
    FakePlayer *player = new FakePlayer();
    int index = g_FakePlayers.AddToTail(player);
    bool foundName = false;
    // Iterate through Player Names and find an Unused one
    for(std::map<char*,int>::iterator it = g_PlayerNames.begin(); it != g_PlayerNames.end(); ++it)
    {
        if(it->second == NAME_AVAILABLE)
        {
            // We found an Available Name. Mark as Unavailable and move it to the end of the list
            foundName = true;
            g_FakePlayers.Element(index)->name = it->first;
            g_PlayerNames.insert(std::pair<char*, int>(it->first, NAME_UNAVAILABLE));
            g_PlayerNames.erase(it); // Remove name since …typedef map<string, string> myMap;
插入新对时myMap,它将使用键string通过自己的字符串比较器进行比较.是否可以覆盖该比较器?例如,我想比较密钥string的长度,而不是字母表.或者还有其他方法可以对地图进行排序吗?