c++ - 通过返回指向 map 的指针访问 map C++

标签 c++ class pointers dictionary

我正在尝试在类中创建一个函数,该函数返回一个指向 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/

相关文章:

android - 为什么在 android list 中关闭 debuggable 会导致数据对齐错误?

c++ - 与 `std::mutex` 同步是否比与 `std::atomic(memory_order_seq_cst)` 慢?

c++从派生类指针获取基类对象?

java - 如何检查子对象是否来自特定类(而不是父类)(Java)

c++ - 如何在类中使用 unique 函数?

c++ - 如何避免在 64 位指针上浪费内存

c++ - Cygwin 未检测到编译器

java - 默认 java 构造函数

c - 在 C 中分配浮点指针

在不知道 C 中类型的情况下将 void 指针转换为 double