Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resize(...)? #1157

Closed
phyz777 opened this issue Jul 9, 2018 · 5 comments
Closed

resize(...)? #1157

phyz777 opened this issue Jul 9, 2018 · 5 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@phyz777
Copy link

phyz777 commented Jul 9, 2018

Hello,

is there a resize() function for arrays, analogous to the resize function of std::vector?

@phyz777
Copy link
Author

phyz777 commented Jul 9, 2018

The following piece of code does not compile, which leads me to the suggestion that currently, this function is not implemented:

#include <iostream>
#include "json.hpp"

int main(int argc, char const *argv[]) {
    nlohmann::json j;

    j["array"] = nlohmann::json::array();

    j["array"].resize(5);

    return 0;
}

Is there another efficient way to store a std::vector in an nlohmann::json::array?
Looping and repeatedly invoking push_back will lead to frequent memory re-allocations in the case of large objects.
In this case, a previous call to j["array"].resize(myVector.size()) would lead to a great performance gain.

Thus, I would suggest implementing the two resize functions analogously to the STL.

@phyz777 phyz777 changed the title resize()? resize(...)? Jul 9, 2018
@nlohmann
Copy link
Owner

nlohmann commented Jul 9, 2018

The library itself does not have a resize() function, but you can access the vector inside a json array with get_ref where you can call std::vector::resize on.

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Jul 9, 2018
@nlohmann
Copy link
Owner

@phyz777 Does this solve your issue?

@phyz777
Copy link
Author

phyz777 commented Jul 13, 2018

Yepp, works fine! Thanks for linking the get_ref<T>() documentation, that helped a lot.

@nlohmann
Copy link
Owner

Cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants