Commonly used data types for C++ exam questions

In the process of using C++ to answer questions, we often encounter data types and data structures that are easy to use in Python but are not used in C++. Here are some summaries. All data types and structures used include but are not limited to
:

Integer, array, dictionary, set, string, small root heap

1. Integer

There is nothing to say about integers. Just end it with int a, but be careful about overflow issues.

2. Array

Arrays in python are very simple, and elements can be added directly through append. However, the length of a regular array in c++ must be determined when it is defined. Unless vector or new is used to create an array with a length of a, a list in python is more like is vector in c++

    // 使用new来创建动态数组
    int len=8;
    int*arr = new int[len];
    // 使用vector来创建动态数组
    int len=8;
    // arr(len)注意是括号不是[],而且里面放的是长度
    // 如果要全部初始化成0,可以这样: vector<int> arr(len,0);
    vector<int> arr(len,0);
    // 初始化为特定的值
    for(int i=0;i<len;i++){
    
    
        arr[i]=i;
    }
    // 直接遍历vector中的元素,类似于 for i in nums
    for(int num:arr){
    
    
        printf("%d\n",num);
    }
    // 对arr进行切片,类似于 b=a[x:y],左闭右开,下面的操作就是
    //     subarr=arr[0:4]
    vector<int> subarr(arr.begin()+0,arr.begin()+4);

    // 追加一个元素,即append
    arr.push_back(8);

    // 排序,即arr.sort(reverse=True),需要#include<algorithm>
    // 最后一个参数greater<int>()用来降序,不写就是升序
    sort(arr.begin(),arr.end(),greater<int>());

	// 原生数组的使用
    // 通过定义一个const变量来设置原生数组的长度
    const int b_size=300;
    int b[b_size];
    // 成批初始化数组,注意memset需要#include<string.h>
    // 特别注意,memset是按照字节操作的,所以3*sizeof(int)
    //  是将b的前3个元素的每一个字节都设置为-1,由于-1的二进制是全为1
    //  所以最终这三个元素都是-1,如果换成其他的数就不好使了,但是这3个数
    //  仍然会是一样的,后面没有初始化的297个数是随机的
    memset(b,-1,3*sizeof(int));
    for(int i=0;i<4;i++)printf("b[%d]=%d\n",i,b[i]);
    int a[7]={
    
    1,2,3,4,5,6,7};
    // c++的原生数组没有size属性,不能直接得到,只能自己算出来
    //    而且,一般用于循环遍历的变量类型是size_t,不是int,也不是unsigned int
    size_t size=sizeof(a)/sizeof(a[0]);
    for(size_t i=0;i<size;i++){
    
    
        // 格式化输出时,size_t类型的变量有属于自己的格式占位符%u,表示无符号整数
        printf("a[%u]=%d\n",i,a[i]);
    }
}

3. Dictionary

The commonly used dictionary in Python is defaultdict, which can specify a default value.
By default, the map pairs in C++ arrange the key-value pairs in ascending order by key, so use them according to the situation.unordered_map

    map<int,int> mymap;
    // 可以先判断这个键在不在里面,如果不在则刻意指定
    if (mymap.find(1)==mymap.end()){
    
    
        mymap[1]=10; // 添加元素和python一样
    }

    // 遍历字典
    for(auto iter=mymap.begin();iter!=mymap.end();iter++){
    
    
        printf("key=%d, value=%d\n",iter->first,iter->second);
    }
    
    // 查看map的大小
    int size=mymap.size();
    // 删除某个键值对,删除成功返回1,否则返回0
    int state = mymap.erase(1);

    // 清空整个字典
    mymap.erase(mymap.begin(),mymap.end());
    // 或者
    mymap.clear();

4. Collection

For C++, the set is an ordered set, but the set in Python is actually an unnecessary set, corresponding to the set in C++unordered_set

    unordered_set<int> m_set;
    // 添加元素
    for(int i=0;i<10;i++){
    
    
        m_set.insert(i);
    }
    // 查找元素
    if(m_set.find(4)!=m_set.end()){
    
    
        printf("元素%d在集合中\n",4);
    }
    // 删除指定的元素,成功返回1,否则返回0
    int is_delete = m_set.erase(1);

Another very important point is that unorder_set and set have different usage ranges. unorder_set is implemented using a hash table, so the internal elements must be hashable, but unlike python, there is no hash function for elements in c++, so It is better to use vector to overload it, so here we define a new type MySet. MySet can directly store vector type data.

#include<unordered_set>
#include<tuple>
#include<iostream>
#include<vector>
using namespace std;

struct VectorHash {
    
    
    size_t operator()(const std::vector<int>& v) const {
    
    
        std::hash<int> hasher;
        size_t seed = 0;
        for (int i : v) {
    
    
            seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
        }
        return seed;
    }
};
using MySet = std::unordered_set<std::vector<int>, VectorHash>;
// 使用也很简单
int main(){
    
    
    MySet mySet;
    mySet.insert({
    
    1,2,3});
    mySet.insert({
    
    3,2,1});
    for(auto it:mySet){
    
    
        cout<<it[0]<<' '<<it[1]<<' '<<it[2]<< endl;
    }
    return 0;
}

5. String

    // 一定要以'\0'结尾
    char s[]={
    
    'h','e','l','l','o','\0'};
    // 这样就不需要以'\0'结尾
    char s2[]="world";
    printf("s=%s\n",s);
    printf("s2=%s\n",s2);
    // 查询长度strlen 需要包含头文件string.h
    printf("s的长度是%d个字符\n", strlen(s));
    printf("s的长度是%d个字符\n", strlen(s));

    // 字符串的切片
    string s3="myboy";
    string sliceed = s3.substr(0,2);
    // cout<<"字符串s[0:2]="<<sliceed<<endl;
    // 注意,string是c++特有的类型,printf不能直接输出,需要转换.c_str()
    printf("字符串s[0:2]=%s\n", sliceed.c_str());

Guess you like

Origin blog.csdn.net/qq_41926099/article/details/131543194