【无标题】

(STL)设计算法的方法。
判断素数问题
判断一个大于 2 的正整数 n 是否为素数,请用至少两种方法实现。;

#include <iostream>
using namespace std;

bool IsPrime(int n)
{
    if (n <= 1) {
        cout << n << "不是素数" << endl;
        return false;
    }
    for (int i = 2; i < n; i++)
    {
        if ((n % i) == 0) {
            cout << n << "不是素数" << endl;
            return false;
        }
    }
    cout << n << "是素数" << endl;
    return true;
}

int main() {
    int a = 7, b = 27, c = 56;
    IsPrime(a);
    IsPrime(b);
    IsPrime(c);
    return 0;
}

方法二

#include <iostream>
using namespace std;

bool IsPrime(int n)
{
    if (n <= 1) {
        cout << n << "不是素数" << endl;
        return false;
    }
    for (int i = 2; i < n; i++)
    {
        if ((n % i) == 0) {
            cout << n << "不是素数" << endl;
            return false;
        }
    }
    cout << n << "是素数" << endl;
    return true;
}

int main() {
    int a = 7, b = 27, c = 56;
    IsPrime(a);
    IsPrime(b);
    IsPrime(c);
    return 0;
}

设计算法,判断回文问题
采用字符串容器存储,设计算法判断该字符串是否为回文。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
	string a;
	cin >> a;
	string b = a;
	reverse(b.begin(), b.end());//反转字符串
	if (a == b) cout << a << "是回文字符" << endl;
	else cout << a << "不是回文字符" << endl;
	return 0;
}

编写程序,对一个含有 n 个元素的队列,出队从队头到队尾的第 k 个元素(1 ≤k≤n),其他队列元素不变。
提示:利用临时队列 tmpque,保存 k-1 个元素,出队第 k 个元素后,将剩
余元素复制至 tmpque

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

int main() {
	queue<int> qu, tmpque;
	int n, a, k;
	cout << "请输入队列大小";
	cin >> n;
	cout << "请输入初始队列";
	for (int i = 0; i < n; i++)
	{
		cin >> a;
		qu.push(a);
	}
	cout << "请输入要出队的元素位置";
	cin >> k;
	for (int i = 0; i < n; i++)
	{
		if (i != (k - 1))
		{
			tmpque.push(qu.front());
			qu.pop();
		}
		else
		{
			cout << "出队元素为" << qu.front() << endl;
			qu.pop();
		}
	}
	while (!tmpque.empty())
	{
		cout << tmpque.front();
		tmpque.pop();
	}
}

一段英文单词由若干单词组成,编写程序提取其中的所有单词。请实现由用
户输入英文,利用字符串存储英文,提取后的单词用向量容器存储。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void solve(string str, vector<string>& words) {
	string w;
	int i = 0;
	int j = str.find(" ");
	while (j != -1) {
		w = str.substr(i, j - i);
		words.push_back(w);
		i = j + 1;
		j = str.find(" ", i);
	}
	if (i <= str.length() - 1) {
		w = str.substr(i);
		words.push_back(w);
	}
}
int main() {
	string str;
	getline(cin, str);
	vector<string> words;
	solve(str, words);
	vector<string>::iterator it;
	for (it = words.begin(); it != words.end(); ++it) {
		cout << *it;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骇梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值