for(auto it : map1){
cout << it.first <<" "<< it.second <<endl;
}
这段for循环条件里的语句是啥意思
这是怎么实现对map的遍历的
这段C++代码使用了foreach循环来遍历一个std::map的内容。
首先解释一下这段代码:
for (auto it : map1) {
cout << it.first << " " << it.second << endl;
}
在这里,map1
是一个 std::map
的对象。该循环使用 auto
关键字推断出 it
的类型,it
是一个键值对(std::pair
)的副本,它包含了map中的key
和value
。
然后,循环通过 it.first
和 it.second
分别访问键值对的键和值,并将它们输出到标准输出(通常是控制台)。
范围for循环会按顺序遍历map1
中的所有键值对,并将每个键值对赋值给it
,然后在循环体中进行处理。
这里的遍历是以无序的方式进行的,因为std::map
是一个关联容器,其内部是按键的大小进行排序的,而不是按插入顺序。如果需要按插入顺序遍历,可以使用 std::unordered_map
。
插入的返回值是返回一个pair对象,所以我们在插入时的返回值都需要修改成一个pair对象,且pair对象的first为插入后的结点的迭代器,second为插入是否成功
pair<iterator, bool> insert(const V& val)
{
if (_header->_parent == nullptr)
{
Node* root = new Node(val);
_header->_parent = root;
root->_parent = _header;
_header->_left = _header->_right = root;
//根节点为黑色
root->_color = BLACK;
return make_pair(iterator(root), true);
}
Node* cur = _header->_parent;
Node* parent = nullptr;
KeyOfValue kov;
//1.寻找到要插入的结点的位置
while (cur)
{
parent = cur;
if (kov(cur->_val) == kov(val))
return make_pair(iterator(cur), false);
else if (kov(cur->_val) > kov(val))
cur = cur->_left;
else
cur = cur->_right;
}
//2.创建节点
cur = new Node(val);
Node* node = cur;
if (kov(parent->_val) > kov(cur->_val))
parent->_left = cur;
else
parent->_right = cur;
cur->_parent = parent;
//3.颜色的修改或者结构的调整
while (cur != _header->_parent && cur->_parent->_color == RED)//不为根且存在连续红色,则需要调整
{
parent = cur->_parent;
Node* gfather = parent->_parent;
if (gfather->_left == parent)
{
Node* uncle = gfather->_right;
//情况1.uncle存在且为红
if (uncle && uncle->_color == RED)
{
parent->_color = uncle->_color = BLACK;
gfather->_color = RED;
//向上追溯
cur = gfather;
}
else
{
if (parent->_right == cur)//情况3
{
RotateL(parent);
swap(cur, parent);
}
//情况2.uncle不存在或者uncle为黑
RotateR(gfather);
parent->_color = BLACK;
gfather->_color = RED;
break;
}
}
else
{
Node* uncle = gfather->_left;
if (uncle && uncle->_color == RED)
{
parent->_color = uncle->_color = BLACK;
gfather->_color = RED;
//向上追溯
cur = gfather;
}
else
{
if (parent->_left == cur)
{
RotateR(parent);
swap(cur, parent);
}
RotateL(gfather);
parent->_color = BLACK;
gfather->_color = RED;
break;
}
}
}
//根节点为黑色
_header->_parent->_color = BLACK;
//更新头结点的左右指向
_header->_left = leftMost();
_header->_right = rightMost();
//return true;
return make_pair(iterator(node), true);
}
在map中也要修改
pair<iterator, bool> insert(const pair<K, T>& kv)
{
return _rbt.insert(kv);
}
T& operator[](const K& key)
{
pair<iterator, bool> ret = _rbt.insert(make_pair(key, T()));
//ret.first 迭代器
//迭代器-> pair<k,v>对象
//pair<k,v>->second,获得v
return ret.first->second;
}
测试: