C++学习杂记190328

  1. memset的使用
    1. 基本格式void *memset(void *s, int ch, size_t n); 第一项为数组的指针,第二项为要替换的字符,第三项为替换长度。
    2. 特别注意:memset按字节对内存块进行初始化,也就是说,正常的对于char类型的数组而言是没有问题的,因为一个char就是一个字节。但是对于其他,比如说希望对int类数组进行初始化,则应当小心,int依据电脑配置不同,一般为32位(4字节)或16位,如果是0,那么没有问题,数字0每一位都是零,但是如果改成1,按照字节去进行填充,设int4字节,则实际上是0000_0001_0000_0001_0000_0001_0000_0001,并不是我们要的1了,这里要注意。
  2. string的使用 
    1. 今天主要想讲一下string用字符赋值时出现的问题,一开始我是这样弄的:
      string str;
      str[0] = 'a';
      str[1] = 'b';
      str[2] = 'c';

      这样最后输出str,得到的是空串,我们看一下reference: 

      std::string::resize

      void resize (size_t n);
      void resize (size_t n, char c);

      Resize string

      Resizes the string to a length of n characters.

      If n is smaller than the current string length, the current value is shortened to its first n character, removing the characters beyond the nth.

      If n is greater than the current string length, the current content is extended by inserting at the end as many characters as needed to reach a size of n. If c is specified, the new elements are initialized as copies of c, otherwise, they are value-initialized characters (null characters).

      这也就是说,在string里,size和capacity是两个区别的概念,当size超出capacity时会发生截断,在上面的错误使用中,一开始str的capacity是0,所以导致后续操作无效。所以先要使用resize开辟空间。注意这里和普通的字符串不同,并不需要为'\0'额外开辟空间。

  3. 结合上面的一个小练习——UVa1368 DNA序列

    #include<iostream>
    
    #define MAXN 55
    #define INF 100000000
    using namespace std;
    
    char list[] = {'A', 'C', 'G', 'T'};
    string arrayGen;
    string dnaList[MAXN];
    int m, n;
    int leastHumming = INF;
    string arrayFit;
    
    void getArray(int p);
    
    int getHamming(string a, string b);
    
    int main() {
        cin >> m >> n;
        for (int i = 0; i < m; i++) {
            cin >> dnaList[i];
        }
        arrayGen.resize(n);
        getArray(0);
        cout << arrayFit;
        return 0;
    }
    
    void getArray(int p) {
        if (p == n) {
            int sum = 0;
    
            for (int i = 0; i < m; i++) {
                sum += getHamming(arrayGen, dnaList[i]);
            }
            if (sum < leastHumming) {
                leastHumming = sum;
                arrayFit = arrayGen;
            }
            return;
        } else {
            for (int i = 0; i < 4; i++) {
                arrayGen[p] = list[i];
                getArray(p + 1);
            }
        }
    }
    
    int getHamming(string a, string b) {
        int cnt = 0;
        for (int i = 0; i < a.length(); i++) {
            cnt += a[i] != b[i];
        }
        return cnt;
    }
    

     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值