我正在尝试在类中创建一个函数,该函数返回一个指向 map 的 const 指针。然后在不同的类中,我可以有一个函数可以接受常量指针,声明迭代器,并将映射的内容复制到一个 vector 中。这个映射类到 vector 类是练习的要求。我以前从未对 map 进行过 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;
}
关于c++ - 通过返回指向 map 的指针访问 map C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851860/