c++ 刷题 错题、编程题整理

1、

c++ 刷题 错题、编程题整理

结果:输出乱码

c++ 刷题 错题、编程题整理

2、

c++ 刷题 错题、编程题整理

    答案选B。

这道题主要考察的知识点是 :全局变量,静态局部变量,局部变量空间的堆分配和栈分配

其中全局变量和静态局部变量时从 静态存储区中划分的空间,

二者的区别在于作用域的不同,全局变量作用域大于静态局部变量(只用于声明它的函数中),

而之所以是先释放 D 在释放 C的原因是,main()函数结束了,释放了D,但是C是在整个程序结束的之前才释放的。

局部变量A 是通过 new 从系统的堆空间中分配的,程序运行结束之后,系统是不会自动回收分配给它的空间的,需要程序员手动调用 delete 来释放。

局部变量 B 对象的空间来自于系统的栈空间,在该方法执行结束就会由系统自动通过调用析构方法将其空间释放。

之所以是 先 A  后 B 是因为,B 是在函数执行到 结尾 "}" 的时候才调用析构函数, 而语句 delete a ; 位于函数结尾 "}" 之前。

3、c++ 查找一个字符串是否是另一个字符串的子串

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string a = "abcdefghijklmn";
    string b = "def";
    string c = "123";
    string::size_type idx;

    // find函数返回的是位置值 无符号整形
    idx = a.find(b);  // c语言中有strstr也可以查找,但是c++中的string效率更高
    if (idx == string::npos)
        cout << "not found!\n";
    else
        cout << "found\n";
    return 0;
}

4、c++ 刷题 错题、编程题整理

#include<iostream>
using namespace std;

int main()
{
    int N, M, P, i, data, d[100] = { 0 }, num[100] = {0}, rank = 1;
    char zifu, delay[100];
    cin >> N >> M >> P;
    for (i = 0; i < N; i++)
    {
        cin >> data;
        d[i] = data;
    }
    for (i = 0; i < M; i++)
    {
        cin >> zifu >> data;
        delay[i] = zifu;
        num[i] = data;
    }
    for (i = 0; i < M; i++)
    {
        if (delay[i] == 'A')
            d[num[i] - 1]++;
        if (delay[i] == 'B')
            d[num[i] - 1]--;
    }
    for (i = 0; i < N; i++)
    {
        if (d[P - 1 ] < d[i])
            rank++;
    }
    /*for (i = 0; i < N; i++)
        cout << d[i] << " ";
    cout << endl;*/
    cout << rank << endl;
}

5、// 判断一个数是否是2的幂


#include<iostream>
#include<list>
using namespace std;

//由于C++中没有直接将10进制转换成2进制的数
void BinaryVector(int n)
{
    if (n < 0)  // 如果是小于0的话,直接不判断
    {
        exit(1);
    }

    // 转换成2进制
    int temp;
    temp = n;
    list<int> L; // 列表,不能使用随机索引,只能按照迭代器索引
    while (temp != 0)
    {
        L.push_front(temp % 2);
        temp = temp / 2;
    }

    // 判断是否是2的幂
    int leiji = 1;
    list<int>::iterator it;
    for (it = L.begin(); it != L.end(); it++)
    {
        if (it == L.begin() && *(it) != 1)
        {
            cout << "false" << endl;
            break;
        }
        else
        {
            if (*it == 0)
                leiji++;
        }
    }
    if (leiji == L.size())
        cout << "true" << endl;
    else
        cout << "false" << endl;
}

void IsTwoPower(int n)
{
}

int main()
{
    int n;
    while (cin >> n)
    {
        BinaryVector(n);
    }
}