C++刷题常用小技巧 [结构化绑定 C++17]

327 阅读1分钟

👉 “Offer 驾到,掘友接招!我正在参与2022春招打卡活动点击查看 活动详情

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1、结构化绑定

  • 假设访问std::pair<int,int>中的一个元素:
std::pair<int,int> a = {1,2};
cout << a.frist << " " << a.second << endl;

与上面的代码段不同,可以将相应的值赋予对应的变量,可读性更高:

std::pair<int,int> a = {1,2};
auto [key,value] = a; //结构化绑定,key对应的是first,value对应的是second
cout << key << value << endl;

比如在遍历map或者unordered_map时,同样可以采用结构化绑定来完成,完整代码如下:

#include <map>
#include <unordered_map>
#include <iostream>
using namespace std;

int main() {
    map<int,int> mp; //unordered_map同理
    for(int i = 0; i < 4; i++) mp[i] = i + 1;
    
    //传统的遍历方式,采用迭代器遍历
    for(auto it = mp.begin(); it != mp.end(); it++) {
        cout << it->first << " " << it->second << endl;
    }
    
    //结构化绑定
    for(auto [key, value] : mp) {
        cout << key << " " << value << endl;
    }
    
    return 0;
}
  • std::tuple 以及自定义结构体

    • 假设需要定义一个学生的结构体信息

      struct Student{
          string name;
          int age;
          char sex;
          double height;
      };
      Student stu = {"Hello", 18, 'M', 175.5};
      cout << stu.name << stu.age << stu.sex << stu.height << endl;
      ​
      
    • 采用std::tuple代替结构体的定义:

      tuple<string, int, char, double> stu = {"Hello", 18, 'M', 175.5};
      
    • std::tuple的两种遍历方式:

      #include <tuple>
      #include <iostream>
      #include <string>
      using namespace std;
      
      int main() {
          tuple<string, int, char, double> stu = {"Hello", 18, 'M', 175.5};
          //传统遍历方式
          cout << get<0>(stu) << " " << get<1>(stu) << " " << get<2>(stu) << " " << get<3>(stu) << endl; 
          //c++ 17 结构化绑定遍历
          auto [name, age, sex, height] = stu;
          cout << name << " " << age << " " << sex << " " << height << endl;
          return 0;
      }
      

2、位运算函数之 __builtin_

  • 判断的二进制中有多少个1
  • 判断n的二进制中1的个数的奇偶性
  • 判断n的二进制末尾最后一个1的位置
  • 断n的二进制末尾后面0的个数
1.__builtin_popcount(unsigned int n) //该函数时判断n的二进制中有多少个1
int n = 15; //二进制为1111
cout<<__builtin_popcount(n)<<endl;//输出4

2.__builtin_parity(unsigned int n) //该函数是判断n的二进制中1的个数的奇偶性
int n = 15;//二进制为1111
int m = 7;//111
cout<<__builtin_parity(n)<<endl;//偶数个,输出0
cout<<__builtin_parity(m)<<endl;//奇数个,输出1

3.__builtin_ffs(unsigned int n) //该函数判断n的二进制末尾最后一个1的位置,从一开始
int n = 1;//1
int m = 8;//1000
cout<<__builtin_ffs(n)<<endl;//输出1
cout<<__builtin_ffs(m)<<endl;//输出4

4.__builtin_ctz(unsigned int n) //该函数判断n的二进制末尾后面0的个数
int n = 1;  //1
int m = 8;   //1000
cout<<__builtin_ctzll(n)<<endl;//输出0
cout<<__builtin_ctz(m)<<endl;//输出3