C/C++:单词排序

对给定的n(1≤n≤20)个英语单词(英语名字长度不超过20),按其字典的顺序输出。

#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
	char a[21][21];
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		scanf("%s",a[i]);
	}
	for(int i=0;i<n-1;i++)
	{
		for(int j=0;j<n-1-i;j++)
		{
			if(strcmp(a[j],a[j+1])>0)
			{
				strcpy(a[n],a[j]);
				strcpy(a[j],a[j+1]);
				strcpy(a[j+1],a[n]);
			}
		}
	}
	for(int i=0;i<n;i++)
	{
		printf("%s\n",a[i]); 
	}
	return 0;
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用OpenMP并行计算单词出现次数的C++代码: ```c++ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <unordered_map> #include <omp.h> using namespace std; // 去除字符串首尾的空格和标点符号 string clean_word(string word) { while (!isalpha(word[0])) { word.erase(0, 1); } while (!isalpha(word[word.size() - 1])) { word.erase(word.size() - 1, 1); } return word; } // 统计单词出现次数 void count_words(unordered_map<string, int>& word_counts, const string& filename) { ifstream file(filename); if (!file.is_open()) { cerr << "Failed to open file: " << filename << endl; exit(1); } string line; while (getline(file, line)) { stringstream ss(line); string word; while (ss >> word) { word = clean_word(word); if (word != "") { #pragma omp atomic word_counts[word]++; } } } } int main(int argc, char** argv) { if (argc < 2) { cerr << "Usage: " << argv[0] << " <filename>" << endl; exit(1); } string filename = argv[1]; unordered_map<string, int> word_counts; double start_time = omp_get_wtime(); count_words(word_counts, filename); double end_time = omp_get_wtime(); // 排序并写入文件 vector<pair<string, int>> word_count_pairs(word_counts.begin(), word_counts.end()); sort(word_count_pairs.begin(), word_count_pairs.end(), [](const pair<string, int>& a, const pair<string, int>& b) { return a.second > b.second; }); ofstream out_file("word_count.txt"); if (!out_file.is_open()) { cerr << "Failed to create output file." << endl; exit(1); } for (const auto& pair : word_count_pairs) { out_file << pair.first << " " << pair.second << endl; } cout << "Time: " << end_time - start_time << "s" << endl; return 0; } ``` 在这个程序中,我们使用 `omp atomic` 关键字来保证多线程同时对一个单词进行修改时,各线程的修改不会互相覆盖。 运行程序时,需要将 OpenMP 支持打开。在 Linux 上,可以使用如下命令编译: ```bash g++ -fopenmp -o wordcount wordcount.cpp ``` 然后使用 `./wordcount <filename>` 来运行程序,其中 `<filename>` 是要统计单词出现次数的文件名。 程序会将统计结果按照“单词 出现次数”的格式保存到 `word_count.txt` 文件中,并在命令行输出程序运行时间。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值