多线程下tcp收数据,接收到的数据类型为泛型数据T,将收到的数据通过Qvetor<T>发送给主线程,其中T是自定义类型。主线程收数据,收到的数据放入QMap<QString,QVctor<T>>中,根据不同的QString和T类型分类数据,比较同一个Map中数据的一致性,思考一下,请用qt写一段代码,代码包含.h和.cpp。
时间: 2024-02-13 15:05:10 浏览: 78
以下是示例代码:
datareceiver.h
```C++
#ifndef DATARECEIVER_H
#define DATARECEIVER_H
#include <QObject>
#include <QVector>
template<typename T>
class DataReceiver : public QObject
{
Q_OBJECT
public:
explicit DataReceiver(QObject *parent = nullptr);
signals:
void dataReceived(const QString& key, const QVector<T>& data);
public slots:
void receiveData(const T& data, const QString& key);
private:
QMap<QString, QVector<T>> m_dataMap;
};
template<typename T>
DataReceiver<T>::DataReceiver(QObject *parent) : QObject(parent)
{
}
template<typename T>
void DataReceiver<T>::receiveData(const T& data, const QString& key)
{
if (!m_dataMap.contains(key)) {
m_dataMap.insert(key, QVector<T>());
}
m_dataMap[key].append(data);
emit dataReceived(key, m_dataMap[key]);
}
#endif // DATARECEIVER_H
```
datareceiver.cpp
```C++
#include "datareceiver.h"
template<typename T>
DataReceiver<T>::DataReceiver(QObject *parent) : QObject(parent)
{
}
template<typename T>
void DataReceiver<T>::receiveData(const T& data, const QString& key)
{
if (!m_dataMap.contains(key)) {
m_dataMap.insert(key, QVector<T>());
}
m_dataMap[key].append(data);
emit dataReceived(key, m_dataMap[key]);
}
```
main.cpp
```C++
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QMap>
#include "datareceiver.h"
struct MyData {
int value1;
QString value2;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
DataReceiver<MyData> receiver;
QMap<QString, QVector<MyData>> dataMap;
QObject::connect(&receiver, &DataReceiver<MyData>::dataReceived, [&](const QString& key, const QVector<MyData>& data) {
dataMap[key] = data;
qDebug() << "Data received for key" << key << ":" << data.size();
});
QThread thread;
thread.start();
for (int i = 0; i < 100; ++i) {
MyData data = { i, "test" };
receiver.moveToThread(&thread);
QMetaObject::invokeMethod(&receiver, "receiveData", Qt::QueuedConnection,
Q_ARG(MyData, data), Q_ARG(QString, "key"));
}
thread.quit();
thread.wait();
qDebug() << "Data map size:" << dataMap.size();
return a.exec();
}
```
阅读全文