c++ - 丢弃限定符访问类中 map 的 vector 时出错?

标签 c++ class dictionary constants private

我在 .h 中定义了一个类:

#ifndef C1_H
#define C1_H

#include <iostream>
#include <map>
#include <string>
#include <vector>

class C1{
        private:
                std::map<std::string, std::vector<int>> cmap;
        public:
                C1();
                ~C1();
                friend std::ostream& operator<< (std::ostream& os, const C1& c);
};

#endif

我在使用输出流功能时遇到问题。在 cpp 文件中,我将其定义为:

ostream& operator<< (ostream& os, const C1& c) {
        vector<string> strlist= //a vector of the strings associated in the map;
        cout << *(strlist.begin()+3) << endl; //this was for testing where the error was
        for (int j = 0; j < 9; j++) {
                int size = c.cmap[*(strlist.begin() + j)].size();
                for (int k = 0; k < size; k++) {
                        os << (c.cmap[*(strlist.begin()+j)]].[begin()+k])<<endl;
                }
        }
        return os;
}

但是得到如下错误:error: passing ‘const std::map,

错误:将'const std::map, std::vector >'作为'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp 的'this'参数传递, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::basic_string; _Tp = std::vector ; _Compare = std::less >; _Alloc = std::allocator, std::vector >>; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::vector; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::basic_string]’ 丢弃限定符 [-fpermissive] int size = t.tokenmap[*(type.begin() + j)].size();

当我从 ostream 运算符重载的定义中删除 const 保护时,这编译得很好,但是,我相信我应该能够使用 const 保护来做到这一点,而且根据我的老师的说法,更好的做法是进入现在的习惯吧。任何人都可以指导我为什么不编译的方向吗?

不过我本来会这样,因为 ostream 是一个友元类,我将能够访问私有(private)成员(像往常一样,我对我的大部分 operator<< 重载使用相同的基本结构并访问私有(private)成员所有时间),但我假设这个问题与以下事实有关,即 const 保护对象内部有一个 vector ,该对象也可能以某种方式受到 const 保护(只是一个想法......我从来没有用 map 重载 <<,所以这对我来说是新的),导致限定符问题。我很想听听你们的任何建议,因为我真的很想用 const 保护来做到这一点,而不是仅仅丢弃它。提前致谢!

最佳答案

在:

int size = c.cmap[*(strlist.begin() + j)].size();

你应该写:

int size = c.cmap.at(*(strlist.begin() + j)).size();

相反。

您将 c 作为 const C1& 传递,这意味着 c.cmap 也是 const

std::map 没有 operator[]const 重载,因为 operator[] 执行一个如果键不存在则插入。这是为了做出如下陈述:

std::map<std::string, int> map;
map["test"] = 1;

工作。

关于c++ - 丢弃限定符访问类中 map 的 vector 时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27119815/

相关文章:

c++ - 计算不同类别的对象数量

scala - 未检测到主类

Python 3 绑定(bind)不起作用

python - "while A:"中的 A 调用了什么操作?

c++ - 套接字:使用不带memcpy的recvfrom将UDP数据放入字对齐的缓冲区中?

python - push_back/emplace_back 一个对象的浅拷贝到另一个 vector 中

c++ - 编辑给定键的无序映射中的值

python - 我如何递归地遍历 2 个字典,并根据另一个字典修改原始字典?

dictionary - 交换 map 项的位置

arrays - 我想从多个 tableView 选择创建一个数组