JSON for Modern C++  3.6.1

◆ 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>
std::pair<iterator, bool> nlohmann::basic_json::emplace ( Args &&...  args)
inline

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]argsarguments to forward to a constructor of basic_json
Template Parameters
Argscompatible 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.311when 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.
1 #include <iostream>
2 #include <nlohmann/json.hpp>
3 
4 using json = nlohmann::json;
5 
6 int main()
7 {
8  // create JSON values
9  json object = {{"one", 1}, {"two", 2}};
10  json null;
11 
12  // print values
13  std::cout << object << '\n';
14  std::cout << null << '\n';
15 
16  // add values
17  auto res1 = object.emplace("three", 3);
18  null.emplace("A", "a");
19  null.emplace("B", "b");
20 
21  // the following call will not add an object, because there is already
22  // a value stored at key "B"
23  auto res2 = null.emplace("B", "c");
24 
25  // print values
26  std::cout << object << '\n';
27  std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n';
28 
29  std::cout << null << '\n';
30  std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n';
31 }
basic_json<> json
default JSON class
Definition: json.hpp:871

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 with
g++ -std=c++11 -Isingle_include doc/examples/emplace.cpp -o emplace 
Since
version 2.0.8

Definition at line 17773 of file json.hpp.