【发布时间】:2020-08-16 22:28:19
【问题描述】:
任务是这样的:要使用 shell 排序对字符串数组进行排序,应该使用 WinAPI 在线程函数中执行排序。最初,程序是使用全局变量编写的,但必须将字符串数组作为参数传递给线程函数,然后开始出现类型转换问题。
strcpy_s(strings[i], strings[i + step]); 上的错误错误日志:E0304 no instance of overloaded function "strcpy_s" matches the argument list。
朋友,这个问题怎么解决?我认为整个问题是我如何将类型从 void* 转换为字符串数组。
#include<iostream>
#include<conio.h>
#include<iomanip>
#include <string.h>
#include <string>
#include <Windows.h>
#include <process.h>
using namespace std;
const int row = 10, n = 32;
__int64 to_int64(FILETIME ft)
{
return static_cast<__int64>(ft.dwHighDateTime) << 32 | ft.dwLowDateTime;
}
DWORD WINAPI shellSort(PVOID pParams) {
int step = row / 2;
char** strings = (char**)pParams;
while (step > 0)
{
for (int i = 0; i < (row - step); i++) {
while (i >= 0 && strcmp(strings[i], strings[i + step]) > 0)
{
char temp[n];
strcpy_s(temp, strings[i]);
strcpy_s(strings[i], strings[i + step]);
strcpy_s(strings[i + step], temp);
i--;
}
}
step = step / 2;
}
return 0;
}
int main()
{
int i;
char strings[row][n];
std::cout << "input " << row << " strings:\n";
for (i = 0; i < row; i++) {
cout << i + 1 << ". ";
cin.getline(strings[i], n);
}
std::cout << "\nOurs strings:\n";
for (i = 0; i < row; i++)
printf("%s\n", strings[i]);
printf("\n");
HANDLE thread = CreateThread(NULL, 0, &shellSort, strings, 0, NULL);
SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL);
WaitForSingleObject(thread, INFINITE);
FILETIME ft[4];
GetThreadTimes(thread, &ft[0], &ft[1], &ft[2], &ft[3]);
std::cout << (to_int64(ft[1]) - to_int64(ft[0])) << endl;
printf("Sorted array:\n");
for (i = 0; i < row; i++)
printf("%s\n", strings[i]);
getchar();
return 0;
}```
【问题讨论】:
-
CreateThread: "可执行文件中调用 C 运行时库 (CRT) 的线程应使用
_beginthreadex和_endthreadex函数进行线程管理,而不是使用 @987654328 @ 和ExitThread[...]"。并发是一个棘手的问题。勤奋是成功的先决条件。 -
嗨 AleksMys,如果答案解决了您最初的问题,您可以 accept 它。对于新出现的问题,请随时提出新问题。
标签: c++ arrays string multithreading winapi