(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;
}
}