|
◆ emplace()
template<template< typename U, typename V, typename... Args > class ObjectType = std::map, template< typename U, typename... Args > class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template< typename U > class AllocatorType = std::allocator, template< typename T, typename SFINAE=void > class JSONSerializer = adl_serializer>
template<class... Args>
Inserts a new element into a JSON object constructed in-place with the given args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from args.
- Parameters
-
[in] | args | arguments to forward to a constructor of basic_json |
- Template Parameters
-
Args | compatible types to create a basic_json object |
- Returns
- a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.
- Exceptions
-
type_error.311 | when called on a type other than JSON object or null; example: "cannot use emplace() with number" |
- Complexity^^ Logarithmic in the size of the container, O(log(size())).
- Example^^ The example shows how emplace() can be used to add elements
- to a JSON object. Note how the
null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key. ^^ 2 #include <nlohmann/json.hpp> 9 json object = {{ "one", 1}, { "two", 2}}; 13 std::cout << object << '\n'; 14 std::cout << null << '\n'; 17 auto res1 = object.emplace( "three", 3); 18 null.emplace( "A", "a"); 19 null.emplace( "B", "b"); 23 auto res2 = null.emplace( "B", "c"); 26 std::cout << object << '\n'; 27 std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n'; 29 std::cout << null << '\n'; 30 std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n'; basic_json<> json default JSON class
Output (play with this example online):^^ {"one":1,"two":2}
null
{"one":1,"three":3,"two":2}
3 true
{"A":"a","B":"b"}
"b" false
^^ The example code above can be translated withg++ -std=c++11 -Isingle_include doc/examples/emplace.cpp -o emplace
- Since
- version 2.0.8
Definition at line 17353 of file json.hpp.
|