Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

emplace_back is pushing the structure into my array (C++)

I’m practicing pushing and popping. For this I’m using the emplace_back function to push a struct into my std::vector.

Here’s my code:

#include <string>
#include <vector>
#include <iostream>
#include <string_view>

struct Person
{
    std::string name{};
    int age{};
};

int main()
{
    std::vector<Person> nums{{"Daniel", 34},
                             {"Jose",   39},
                             {"Martin", 22}
                              };

    nums.emplace_back("Malena", 30);


    for (auto const& a : nums)
        std::cout << a.name << " " << a.age << '\n';

    return 0;
}

Error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In file included from /Users/xxx/CLionProjects/test/main.cpp:1:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string:504:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string_view:175:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__string:57:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:643:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/memory:1881:31: error: no matching constructor for initialization of 'Person'
            ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
                              ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/memory:1773:18: note: in instantiation of function template specialization 'std::__1::allocator<Person>::construct<Person, char const (&)[7], int>' requested here
            {__a.construct(__p, _VSTD::forward<_Args>(__args)...);}

Any help is appreciated.

>Solution :

This requires C++20. Some options in C++17 or older are:

  • Define a constructor for Person:

    struct Person
    {
        Person(const std::string& name, int age)
           : name(name)
           , age(age)
        {}
    
        std::string name;
        int age = 0;
    };
    
  • Pass a constructed object explicitly (C++14):

    nums.emplace_back(Person{"Malena", 30});
    
  • Use push_back instead with a braced initializer list (C++14):

    nums.push_back({"Malena", 30});
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading