簡體   English   中英

如何檢查std :: map鍵是否存在以用於對象的屬性更新,否則插入一個新鍵?

[英]how check if std::map key exists for object's property update otherwise insert a new one?

在Java中,有時我會這樣做

Map<String, POJO> objmap = new HashMap<String, POJO>();
POJO obj = null;
if ((obj = objMap.get(key)) == null) {
    obj = new POJO();
    objMap.put(key, obj);
}
obj.setName("something");
obj.setAddress("yeah");

使用std :: map在c ++中執行類似操作的最佳實踐是什么? 在地圖中創建obj(如果不存在),然后更新其屬性?

像這樣:

void insert_or_update(const K & k, const T & t, std::map<K, T> & m)
{
    auto p = m.insert(std::make_pair(k, t));
    if (!p.second) p.first->second = t;
}

要么:

    m[k] = t;

后者要求T是默認可構造和可分配的。

在C ++ 17中,您還可以說:

m.insert_or_assign(k, t);

與上面的構造相比,這具有更少的限制,並且返回有關插入是否發生以及元素迭代器的信息。

您想使用insert函數,它返回一個迭代器和一個關於是否插入新對象的布爾值:

typedef map<int,void*> M;
M m;
auto insertion = m.insert(M::value_type(0,nullptr));
if (insertion.second) {
insertion.first->second = new... (// allocate your item or whatever, this is the iterator to it)
}

您可以編寫objmap[key] = value

參見: http : //www.cplusplus.com/reference/map/map/operator[]/

 std::map<std::string, POJO> mapStr2Pojo;
 mapStr2Pojo["something"].setName("something");
 mapStr2Pojo["something"].setAddress("yeah");

std :: map <>的operation []如果找不到該對象,則將其插入。

插入操作檢查每個插入的元素是否具有與容器中已有元素相同的鍵,如果是,則不插入該元素,將迭代器返回到此現有元素

    if ( !myMap.insert( std::make_pair( key, value ) ).second ) 
    {
        //  Element already present...
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM