[Learning]C++语法

  "C++中的一些语法使用"

Posted by Stephen.Ri on November 16, 2017

extern 全局变量

在.h头文件中声明extern,如 extern int tmp;

在.cpp文件中定义变量,如 int tmp = 1;

unordered_map

unordered_mapmap类似,都是存储key-value的值,可以通过key快速检索到value

不同的是unordered_map不会根据key的大小进行排序,即map中的元素是按照二叉搜索树存储的,而unordered_map是根据keyhash值判断元素是否相同。

所以,当需要内部元素自动排序时,使用map;不需要排序时,使用unordered_map提高查找效率。

注意,由于unordered_map内部采用hash函数实现,因此find()函数的平均查找复杂度O(1)最差查找复杂度O(n)

使用实例如下:

#include <iostream>
#include <string>
#include <unordered_map>
 
int main()
{
    // Create an unordered_map of three strings (that map to strings)
    std::unordered_map<std::string, std::string> u = {
        {"RED","#FF0000"},
        {"GREEN","#00FF00"},
        {"BLUE","#0000FF"}
    };
 
    // Iterate and print keys and values of unordered_map
    for( const auto& n : u ) {
        std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
    }
 
    // Add two new entries to the unordered_map
    u["BLACK"] = "#000000";
    u["WHITE"] = "#FFFFFF";
 
    // Output values by key
    std::cout << "The HEX of color RED is:[" << u["RED"] << "]\n";
    std::cout << "The HEX of color BLACK is:[" << u["BLACK"] << "]\n";

    // find value by key
    auto search = u.find("RED");
    if(search != u.end()) {
        std::cout << "Found " << search->first << " " << search->second << '\n';
    }
    else {
        std::cout << "Not found\n";
    }
 
    return 0;
}