emplace_back 正在将结构推入我的数组(C++)

问题描述 投票:0回答:2

我正在练习推和弹出。为此,我使用

emplace_back
函数将结构推入我的数组中。

这是我的代码:

#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;
}

错误:

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)...);}

如有任何帮助,我们将不胜感激。

c++ struct push emplace
2个回答
0
投票

这需要 C++20。 C++17 或更早版本中的一些选项是:

  • Person
  • 定义一个构造函数
  • 显式传递对象:
    nums.emplace_back(Person{"Malena", 30});
  • 使用push_back代替带花括号的初始值设定项列表:
    nums.push_back({"Malena", 30});

0
投票

编译在 C++ 20 中编译得很好。
请参阅演示1

如果必须使用旧版本的 C++,则应将以下构造函数添加到

Person

Person(std::string const & n, int a) : name(n), age(a) {}

参见演示2

© www.soinside.com 2019 - 2024. All rights reserved.