仅使用迭代器访问c++stl映射
access c++ stl map only using iterator
我想要一个将map变量作为私有变量的类:
class CTest{
private:
std::map<int, int> m_map;
public:
std::map<int int>::iterator get_iterator();
void add(int key, int val) { m_map[key] = val; }
}
在函数some_action()
中,我是否只能使用get_iterator()
迭代映射,例如:
CTest c;
/* here i want to go through that m_map, but i cannot have access to it */
void some_actoin(){
???
}
int main(void){
c.add(1, 1);
c.add(2, 3);
some_action();
}
问候J.
如果你真的想这样做,你可以添加公共方法来获得开始和结束迭代器,例如
class CTest{
private:
std::map<int, int> m_map;
public:
std::map<int, int>::const_iterator cbegin() { return m_map.cbegin(); }
std::map<int, int>::const_iterator cend() { return m_map.cend(); }
};
CTest c;
void some_action()
{
for (std::map<int, int>::const_iterator it = c.cbegin(); it != c.cend(); ++it)
{
// do action
}
}
简短的答案是否定的。您至少需要m_map.end()来结束循环。然而,我建议不要使用get_iterator()
,而是在类中添加类似for_each
的内容来接受std::function
,并使用std::for_each
将其应用于映射中的所有元素。这样一来,您的acton甚至不需要知道它迭代了映射,它只是完成了自己的工作。
您需要一个"开始"和一个"结束"来迭代它。
例如
class CTest{
private:
std::map<int, int> m_map;
public:
std::map<int int>::const_iterator cbegin();
std::map<int int>::const_iterator cend();
void add(int key, int val) { m_map[key] = val; }
}
void some_actoin()
{
for(std::map<int int>::const_iterator it = c.cbegin(); it != c.cend(); ++it)
{
const auto& val = *it;
}
// C++11
for(const auto& val : c)
{
}
}
相关文章:
- STL映射比较器能否以某种方式获取指向映射本身的指针?
- 在 c++ stl 映射中,删除具有重复值的条目
- C++ STL 映射同时更新所有值
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- 无法将元素添加到 STL 映射
- 为什么不能在STL映射中插入值
- 在 stl 映射和列表 (c++) 上进行迭代的泛型循环
- 未签名的char数组到stl ::映射或其他容器中的键
- 整数和元组的静态 STL 映射返回 0
- 指向类的指针的 STL 映射的 SWIG 类型图
- 将 STL 映射存储到 Boost ConstBufferSequence 中
- 如何在下一次函数调用中使用 STL 映射擦除从最后一个位置
- 如何使用密钥 2 更新 STL 映射键 1 并将值复制到键 2 中
- 为什么当代码尝试在 STL 映射中查找键时出现分段错误
- 快速插入STL映射
- C STL映射中的SegFault由于过程退出期间的静态可变清理而找到
- 如何将 STL 映射保存到文件C++
- C++STL映射键和值工作不正常
- STL 映射自定义比较器
- 带有内存比较的 STL 映射.如何在运行时设置比较块大小