gpt4 book ai didi

c++ - 在 std::map 中存储对象

转载 作者:太空宇宙 更新时间:2023-11-04 16:00:31 25 4
gpt4 key购买 nike

我想在 std::map 中存储一个类的对象。这是一个工作示例,展示了我目前是如何做的

#include <iostream>
#include <map>

class A
{
private:
int a;
std::string b;

public:
A(int init_a, std::string init_b) : a(init_a), b(init_b){};
void output_a() {std::cout << a << "\n";}
};

int main()
{
std::map<size_t, A> result_map;
for (size_t iter = 0; iter < 10; ++iter)
{
A a(iter, "bb");
result_map.insert(std::make_pair(iter, a));
}

return 0;
}

我对这个例子有两个问题:

  1. 在上述情况下,这是在 std::map 中存储对象的专业 C++ 方式吗?或者我应该创建一个指向 A 对象的指针并存储它吗?我喜欢第一个(当前)选项,因为我不必通过使用 newdelete 自己担心内存管理 - 但最重要的是我想做一些事情

  2. 我将如何调用 result_map[0] 的成员函数?我天真地尝试了 result_map[0].output_a(),但这给了我错误:error: no matching function for call to 'A::A()'

最佳答案

Is this the professional C++-way to store objects in an std::map in the above case?

很好,更简单的代码可以是:

result_map.emplace(iter, A(iter, "bb") );

您应该使用任何您认为更具可读性的内容。顺便说一句,调用整数计数器 iter 并不是编写可读代码的方法。

How would I go about calling a member function of, say, result_map[0]?

你最好使用std::map::find:

auto f = result_map.find( 0 );
if( f != result_map.end() ) f->output_a();

operator[] 在您的情况下存在问题 - 如果该索引不存在对象,但您没有 A 的默认构造函数,则它必须创建和实例化。

关于c++ - 在 std::map 中存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45334325/

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