通过返回指向映射的指针 C++ 来访问映射
accessing a map by returning a pointer to it c++
我正在尝试在一个返回指向映射的常量指针的类中创建一个函数。然后在不同的类中,我可以有一个函数,它可以接受常量指针,声明迭代器,并将映射的内容复制到向量中。此映射类到向量类是练习的要求。我以前从未做过 ptrs 到地图,也没有编译器喜欢的语法。这是我在 Map 中的函数声明:
class WordCount
{
public:
WordCount();
~WordCount();
void word_insert(std::string clean_word);
void print_all();
const std::map<std::string, int> * get_map();
private:
std::map<std::string, int> m_word_counts;
std::map<std::string, int>::iterator m_it;
std::pair<std::map<std::string, int>::iterator, bool> m_ret;
};
但是当我尝试这样定义函数(或我尝试过的许多变体)时,我得到一个转换错误。以下需要更改哪些内容?
const map<string, int > * WordCount::get_map()
{
const map<string, int > *ptr = m_word_counts;
return ptr;
}
--
我只会返回一个引用。
const map<string, int > & WordCount::get_map()
{
const map<string, int > &ptr = m_word_counts;
return ptr;
}
const map<string, int > *ptr = &m_word_counts;
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 智能指针作为无序映射键,并通过引用进行比较
- C++:映射结构中的结构指针
- 如何创建对象函数指针C++映射?
- 整数键映射到头文件中的成员函数指针
- C++在一个映射中存储不同的指针类型(并处理销毁)
- 添加要映射的对象的唯一指针
- 通过指针或引用将映射传递给函数?
- 在映射中存储模板类函数指针
- c++:复制、删除和运算符=在原始指针映射中
- 将唯一指针插入std::映射
- 在循环(C++)中用新指针填充映射
- C++:如何初始化包含具有给定键的指针列表的映射
- 如何将带指针的结构插入到映射中
- 重构MFC消息映射以包括完全限定的成员函数指针
- C 正确的方法来初始化和处理映射指针
- 定义基于模板的映射指针,以便在验证范围时将 int 解析为枚举
- C++中的静态无序映射指针初始化
- 动态分配映射指针值
- 如何在c++中维护映射指针的向量