gpt4 book ai didi

c++ - 单行在 map 中初始化C++对象

转载 作者:行者123 更新时间:2023-12-01 15:04:55 25 4
gpt4 key购买 nike

初始化类并直接分配给unordered_map的正确方法是什么?

#include <string>

#include <unordered_map>
int main() {
std::unordered_map<std::string, Foo> s;
// Foo foo{1};
s["test"] = Foo(1); // this is bad
return 0;
}

oo
class Foo {
public:
Foo(int x)
: x_(x) {}

private:
int x_;
};

现在我明白了
main.cpp:19:4: note: in instantiation of member function 'std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo, std::hash<std::__cxx11::string>, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo> > >::operator[]' requested here
s["test"] = Foo(1);
^
Foo.h:3:5: note: candidate constructor not viable: requires single argument 'x', but no arguments were provided
Foo(int x)
^
Foo.h:1:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
class Foo {
^
Foo.h:1:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided

问题在于 s["test"] = Foo(1)

最佳答案

当您想使用operator[]时,映射中的元素必须是默认可构造的,因为当映射中尚不存在给定键的值时,它将默认构造该值。使您的Foo默认为可构造的,或改用 insert emplace

默认可构造的Foo:

class Foo {
public:
Foo(int x = 0) // <- can be called without parameters
: x_(x) {}

private:
int x_;
};

关于c++ - 单行在 map 中初始化C++对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62051732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com