<8> 其实,队列也可以这么来替代。

本文介绍了一种使用两个栈来模拟队列行为的方法,并提供了一个具体的C++实现示例。该方法通过一个栈存储数据,另一个栈在需要获取队列头部元素时用于临时存储数据并取出顶部元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两个栈来代替一个队列,一个栈正常存储数据,另一个栈在执行top()时候存储“从第一个栈中去取出来的数据”,并将第二个栈的顶端数据弹出即可。

#include <iostream>
#include <malloc.h>
#include <algorithm>
#include <functional>



//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
// 基类

class UnCopyable{
public:
	UnCopyable();
	~UnCopyable();

private:
	UnCopyable(const UnCopyable& e);
	UnCopyable& operator=(const UnCopyable& e);
};

UnCopyable::UnCopyable(){

}

UnCopyable::~UnCopyable(){

}

UnCopyable::UnCopyable(const UnCopyable& e) {
	*this = e;
}
UnCopyable& UnCopyable::operator=(const UnCopyable&) {
	return *this;
}


// ------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------
// 基类UnCopyable是为了阻止MyQueue可以被赋值和拷贝

class MyQueue : private UnCopyable {

public:
	MyQueue( unsigned int size ) 
		: m_Top( -1 ), m_Top_2(-1), 
		  m_MAX( -100000 ), m_Min( 100000 )
	{
		m_VAPACITY = size;
		m_Data = (int*)malloc(sizeof(int)*m_VAPACITY);
		m_Data_2 = (int*)malloc(sizeof(int)*m_VAPACITY);
	}
	~MyQueue();
private:
	int *m_Data;													//	存取值的数组
	int *m_Data_2;													//	存取值的数组
	int  m_Top;														//  栈顶索引
	int  m_Top_2;													//  栈顶索引
	int  m_MAX;														//  数组中的最大值
	int  m_Min;														//  数组中的最小值
	unsigned int m_VAPACITY;										//  栈的容量
public:
	enum QueueSort
	{
		less,
		greater
	};

	unsigned int QueueVapacity() const;								//  栈的容量
	unsigned int QueueMax() const;									//  栈最大
	unsigned int QueueMin() const;									//  栈最小
public:
	bool isEmpty();													//  判断栈是否为空
	bool isFull();													//  判断栈是否满了
	bool isEmpty_2();												//  判断栈是否为空
	bool isFull_2();												//  判断栈是否满了
	void pop();														//  出栈(删除栈顶元素)
	void push( int value );											//  入栈
	void pop_2();													//  出栈(删除栈顶元素)
	void push_2(int value);											//  入栈
	unsigned int Top();												//  取值
	unsigned int Top_2();
	unsigned int Tops();
	int max();														//  栈中最大值(版本1)
	int min();														//  栈中最小值(版本1)
	int max1();														//  栈中最大值(版本2)
	int min1();														//  栈中最小值(版本2)
	void QueueOrder( QueueSort Strategy );							//  将栈中的元素排序
};


unsigned int MyQueue::QueueVapacity() const {
	return m_VAPACITY;
}

unsigned int MyQueue::QueueMax() const {
	return m_MAX;
}

unsigned int MyQueue::QueueMin() const {
	return m_Min;
}

bool MyQueue::isEmpty(){
	return m_Top == -1;
}

bool MyQueue::isEmpty_2() {
	return m_Top_2 == -1;
}

bool MyQueue::isFull() {
	return m_Top == m_VAPACITY - 1;
}

bool MyQueue::isFull_2() {
	return m_Top_2 == m_VAPACITY - 1;
}

void MyQueue::pop() {
	try{
		 if (!isEmpty()) {
			 m_Top--;
		 }
		 else{
			 std::cout << "the Queue is empty." << std::endl;
		 }
	}
	catch (const std::exception& e){
		std::cout << e.what() << std::endl;
	}	
}

void MyQueue::push( int value ) {
	try{
		if (!isFull()) {
			m_Data[m_Top++] = value;
		}
		else{
			std::cout << "the Queue is full." << std::endl;
		}
	}
	catch (const std::exception& e){
		std::cout << e.what() << std::endl;
	}
}

void MyQueue::pop_2() {
	try {
		if (!isEmpty_2()) {
			m_Top_2--;
		}
		else {
			std::cout << "the Queue is empty." << std::endl;
		}
	}
	catch (const std::exception& e) {
		std::cout << e.what() << std::endl;
	}
}

void MyQueue::push_2(int value) {
	try {
		if (!isFull_2()) {
			m_Data_2[m_Top_2++] = value;
		}
		else {
			std::cout << "the Queue is full." << std::endl;
		}
	}
	catch (const std::exception& e) {
		std::cout << e.what() << std::endl;
	}
}

unsigned int MyQueue::Top() {
	if (!isEmpty()) {
		int Temp = m_Data[m_Top];
		m_Top--;
		return Temp;
	}
}

unsigned int MyQueue::Top_2() {
	if (!isEmpty()) {
		int Temp = m_Data_2[m_Top_2];
		m_Top_2--;
		return Temp;
	}
}

unsigned int MyQueue::Tops() {
	if (!isEmpty_2()) {
		
		// 第一步(判断m_data_2不是空,直接将m_data_2的顶端数据倒出)
		return Top_2();
	}
	else{

		// 第二步(判断m_data_2是空,直接将m_data_1的顶端数据全部数据倒出到m_data_2里,然后将m_data_2的顶端数据倒出)
		while ( !isEmpty() ){
			push_2(Top());
		}

		return Top_2();
	}
}

int MyQueue::max(){
	if (!isEmpty()) {
		std::sort(m_Data, m_Data + m_Top + 1, std::greater<int>());
		return m_Data[0];
	}
}

int MyQueue::min() {
	if (!isEmpty()) {
		std::sort(m_Data, m_Data + m_Top + 1, std::less<int>());
		return m_Data[0];
	}
}

int MyQueue::max1() {
	if (!isEmpty()) {
		m_MAX = m_Data[0];
		for ( size_t i = 0; i <= m_Top; i++ ){
			if (m_Data[i] > m_MAX) {
				m_MAX = m_Data[i];
			}
		}

		return m_MAX;
	}

	return 0x1000000;
}

void MyQueue::QueueOrder( QueueSort Strategy ) {
	switch (Strategy){
			case QueueSort::greater:	
				std::sort(m_Data, m_Data + m_Top + 1, std::greater<int>());
			case QueueSort::less:
				std::sort(m_Data, m_Data + m_Top + 1, std::less<int>());
			default:
				break;
	}
}

int MyQueue::min1() {
	if (!isEmpty()) {
		m_Min = m_Data[0];
		for ( size_t i = 0; i <= m_Top; i++ ) {
			if (m_Data[i] < m_Min) {
				m_MAX = m_Data[i];
			}
		}
	}

	return 0x1000000;
}

MyQueue::~MyQueue(){

}

int main() {

	MyQueue Q(3);
	Q.push(1);
	Q.push(2);
	Q.push(3);

	std::cout << Q.Tops() << std::endl;
	std::cin.get();
}


<template> <view class="chat-container"> <!-- 消息列表区域 --> <view class="message-list" ref="messageList"> <view v-for="(message, index) in messages" :key="index" :class="['message', message.isUser ? 'user-message' : 'system-message']"> <!-- 用户消息 --> <view v-if="message.isUser" class="message-content"> <view class="avatar user-avatar">👤</view> <view class="bubble"> <p>{{ message.content }}</p> <view v-if="message.taskId" class="task-info"> <span class="tag">{{ message.type === 'image' ? '图片生成' : '视频生成' }}</span> <span class="status" :class="message.status">{{ getStatusText(message.status) }}</span> </view> </view> </view> <!-- 系统消息 --> <view v-else class="message-content"> <view class="avatar system-avatar">🤖</view> <view class="bubble"> <!-- 生成状态 --> <view v-if="message.status === 'pending'" class="generating"> <view class="loading-spinner"></view> <p>正在生成{{ message.type === 'image' ? '图片' : '视频' }},请稍候...</p> </view> <!-- 生成结果 --> <view v-if="message.status === 'completed'"> <view v-if="message.type === 'image'"> <image style="width: 50rpx; height: 50rpx;" :src="message.url" alt="生成的图片" @click="previewImage(message.url)" /> <p class="hint">点击图片查看大图</p> </view> <view v-else-if="message.type === 'video'"> <video controls :src="message.url"></video> <p class="hint">视频生成完成</p> </view> </view> <!-- 错误提示 --> <view v-if="message.status === 'error'" class="error-message"> <p>⚠️ 生成失败: {{ message.error }}</p> </view> </view> </view> </view> </view> <!-- 输入区域 --> <view class="input-area"> <textarea v-model="inputText" placeholder="输入描述文字..." @keyup.enter="sendMessage"></textarea> <view class="action-buttons"> <button @click="generateImage" :disabled="!inputText.trim()">生成图片</button> <button @click="generateVideo" :disabled="!inputText.trim()">生成视频</button> </view> </view> <!-- 任务队列悬浮窗 --> <view class="task-queue" v-if="taskQueue.length > 0"> <h4>生成队列 ({{ processingTask ? '处理中' : '等待中' }})</h4> <ul> <li v-for="(task, index) in taskQueue" :key="task.id" :class="['task-item', index === 0 && processingTask ? 'processing' : '']"> <span class="task-type">{{ task.type === 'image' ? '🖼️' : '🎬' }}</span> <span class="task-prompt">{{ task.prompt }}</span> <span class="task-status">{{ getQueueStatus(index) }}</span> </li> </ul> </view> </view> </template> <script> export default { data() { return { inputText: '', messages: [], taskQueue: [], processingTask: null, nextTaskId: 1 }; }, mounted() { // 添加初始欢迎消息 this.addSystemMessage('欢迎使用AI生成助手!请描述您想要生成的图片或视频内容。'); }, methods: { // 添加用户消息 addUserMessage(content, type) { this.messages.push({ id: Date.now(), isUser: true, content, type, status: 'queued', taskId: this.nextTaskId++ }); this.scrollToBottom(); }, // 添加系统消息 addSystemMessage(content, type = 'text', status = 'completed') { this.messages.push({ id: Date.now(), isUser: false, content, type, status }); this.scrollToBottom(); }, // 滚动到底部 scrollToBottom() { this.$nextTick(() => { const container = this.$refs.messageList; container.scrollTop = container.scrollHeight; }); }, // 生成图片 generateImage() { if (!this.inputText.trim()) return; const prompt = this.inputText.trim(); this.inputText = ''; // 添加用户消息 this.addUserMessage(prompt, 'image'); // 添加到任务队列 this.addToQueue({ type: 'image', prompt, taskId: this.nextTaskId - 1 }); }, // 生成视频 generateVideo() { if (!this.inputText.trim()) return; const prompt = this.inputText.trim(); this.inputText = ''; // 添加用户消息 this.addUserMessage(prompt, 'video'); // 添加到任务队列 this.addToQueue({ type: 'video', prompt, taskId: this.nextTaskId - 1 }); }, // 添加到任务队列 addToQueue(task) { this.taskQueue.push(task); // 添加系统提示消息 this.addSystemMessage(`您的${task.type === 'image' ? '图片' : '视频'}生成任务已加入队列`, 'text'); // 如果没有正在处理的任务,开始处理 if (!this.processingTask) { this.processQueue(); } }, // 处理任务队列 async processQueue() { if (this.taskQueue.length === 0) { this.processingTask = null; return; } // 获取第一个任务 this.processingTask = this.taskQueue[0]; // 更新消息状态为处理中 this.updateMessageStatus(this.processingTask.taskId, 'pending'); try { // 模拟生成过程(实际应调用API) const result = await this.generateContent(this.processingTask); // 添加系统结果消息 this.addSystemMessage(result.url, this.processingTask.type, 'completed'); // 更新消息状态为完成 this.updateMessageStatus(this.processingTask.taskId, 'completed'); // 从队列中移除已完成任务 this.taskQueue.shift(); // 处理下一个任务 this.processQueue(); } catch (error) { // 添加错误消息 this.addSystemMessage(`生成失败: ${error.message}`, 'text', 'error'); // 更新消息状态为错误 this.updateMessageStatus(this.processingTask.taskId, 'error', error.message); // 从队列中移除失败任务 this.taskQueue.shift(); // 处理下一个任务 this.processQueue(); } }, // 更新消息状态 updateMessageStatus(taskId, status, error = '') { const message = this.messages.find(m => m.taskId === taskId); if (message) { message.status = status; if (error) message.error = error; } }, // 生成内容(模拟) generateContent(task) { return new Promise((resolve, reject) => { // 模拟API调用延迟 setTimeout(() => { if (Math.random() > 0.1) { // 90%成功率 resolve({ url: task.type === 'image' ? `https://picsum.photos/400/300?random=${Math.floor(Math.random() * 1000)}` : 'https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4' }); } else { reject(new Error('AI生成服务暂时不可用')); } }, task.type === 'image' ? 3000 : 6000); // 图片3秒,视频6秒 }); }, // 预览图片 previewImage(url) { // 实际项目中应使用图片预览组件 window.open(url, '_blank'); }, // 获取状态文本 getStatusText(status) { const statusMap = { queued: '队列中', pending: '生成中', completed: '已完成', error: '失败' }; return statusMap[status] || status; }, // 获取队列状态 getQueueStatus(index) { if (index === 0 && this.processingTask) return '处理中'; return `等待 ${index}`; } } }; </script> <style scoped> .chat-container { display: flex; flex-direction: column; height: 100vh; max-width: 800px; margin: 0 auto; background-color: #f0f2f5; position: relative; } .message-list { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 15px; } .message-content { display: flex; max-width: 80%; } .user-message .message-content { margin-left: auto; flex-direction: row-reverse; } .system-message .message-content { margin-right: auto; } .avatar { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; flex-shrink: 0; margin: 0 10px; } .user-avatar { background-color: #1890ff; color: white; } .system-avatar { background-color: #52c41a; color: white; } .bubble { padding: 12px 15px; border-radius: 18px; position: relative; max-width: 100%; word-break: break-word; } .user-message .bubble { background-color: #1890ff; color: white; border-bottom-right-radius: 5px; } .system-message .bubble { background-color: white; color: #333; border-bottom-left-radius: 5px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); } .task-info { margin-top: 8px; font-size: 0.8em; opacity: 0.8; display: flex; align-items: center; gap: 8px; } .tag { background: rgba(255, 255, 255, 0.2); padding: 2px 6px; border-radius: 4px; } .status { padding: 2px 6px; border-radius: 4px; } .status.queued { background-color: #f0f0f0; color: #666; } .status.pending { background-color: #e6f7ff; color: #1890ff; } .status.completed { background-color: #f6ffed; color: #52c41a; } .status.error { background-color: #fff2f0; color: #ff4d4f; } .generating { display: flex; align-items: center; gap: 10px; } .loading-spinner { width: 20px; height: 20px; border: 3px solid rgba(0, 0, 0, 0.1); border-top-color: #1890ff; border-radius: 50%; animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } .input-area { padding: 15px; background-color: white; border-top: 1px solid #e8e8e8; border-radius: 15px; } textarea { width: 95%; min-height: 60px; padding: 10px; border: 1px solid #d9d9d9; border-radius: 4px; resize: none; font-family: inherit; border-radius: 15px; } .action-buttons { display: flex; gap: 10px; margin-top: 10px; } button { flex: 1; /* padding: 10px; */ background-color: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.3s; } button:disabled { background-color: #bfbfbf; cursor: not-allowed; } button:hover:not(:disabled) { background-color: #40a9ff; } .task-queue { position: absolute; top: 80rpx; right: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); padding: 15px; max-width: 300px; z-index: 100; } .task-queue h4 { margin-top: 0; margin-bottom: 10px; color: #333; } .task-item { padding: 8px 0; border-bottom: 1px solid #f0f0f0; display: flex; align-items: center; gap: 10px; } .task-item:last-child { border-bottom: none; } .task-type { font-size: 1.2em; } .task-prompt { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .task-status { font-size: 0.85em; color: #666; } .task-item.processing .task-status { color: #1890ff; font-weight: bold; } image, video { max-width: 100%; border-radius: 8px; display: block; margin-top: 5px; } video { max-width: 400px; } .hint { font-size: 0.8em; color: #666; margin-top: 5px; } .error-message { color: #ff4d4f; } </style> 你看看 为什么系统消息有一个空的气泡 就是我点击生成图片之后生成成功就会出现一个 开始没有发消息也出现了一个 解决一下
最新发布
08-05
以下代码有问题吗,主要是关于队列缓冲区的读写的。 #ifndef __CONCURRENT_QUEUE_H__ #define __CONCURRENT_QUEUE_H__ #include "CarerayVersion.h" #include <queue> #include <mutex> #include <condition_variable> #include <functional> using namespace std; template<typename Data> class concurrent_queue { public: concurrent_queue() { m_bStopWaiting = false; } virtual ~concurrent_queue() { } void push(Data&& data) { unique_lock<mutex> oAutoLock(the_mutex); the_queue.push(std::forward<Data>(data)); // Manual unlocking is done before notifying, // to avoid waking up the waiting thread only to block again oAutoLock.unlock(); the_condition.notify_one(); } // void push(Data& data) // { //unique_lock<mutex> oAutoLock(the_mutex); //the_queue.push(data); //// Manual unlocking is done before notifying, //// to avoid waking up the waiting thread only to block again //oAutoLock.unlock(); //the_condition.notify_one(); // } void force_stop_waiting() { unique_lock<mutex> oAutoLock(the_mutex); m_bStopWaiting = true; the_condition.notify_one(); } void reset_stop_waiting() { unique_lock<mutex> oAutoLock(the_mutex); m_bStopWaiting = false; } bool empty() const { lock_guard<mutex> oAutoLock(the_mutex); return the_queue.empty(); } int size() const { lock_guard<mutex> oAutoLock(the_mutex); return the_queue.size(); } bool try_pop(Data& popped_value) { lock_guard<mutex> oAutoLock(the_mutex); if(the_queue.empty()) { return false; } popped_value=move(the_queue.front()); the_queue.pop(); return true; } void force_pop() { lock_guard<mutex> oAutoLock(the_mutex); if (!the_queue.empty()) { the_queue.pop(); } } bool clear() { lock_guard<mutex> oAutoLock(the_mutex); if(the_queue.empty()) { return true; } queue<Data> empty_queue; the_queue.swap(empty_queue); return true; } bool wait_and_pop(Data& popped_value, int nWaitMs = -1) { bool isWaited = false; unique_lock<mutex> oAutoLock(the_mutex); if (nWaitMs > 0) { chrono::steady_clock::time_point oUtilTime = chrono::steady_clock::now() + chrono::milliseconds(nWaitMs); while (chrono::steady_clock::now().time_since_epoch().count() < oUtilTime.time_since_epoch().count()) { the_condition.wait_until(oAutoLock, oUtilTime, [&]() { return is_not_empty() || m_bStopWaiting; }); if (!the_queue.empty()) { popped_value = move(the_queue.front()); the_queue.pop(); isWaited = true; break; } if (m_bStopWaiting) { break; } } } else { while (true) { the_condition.wait(oAutoLock, [&]() { return is_not_empty() || m_bStopWaiting; }); if (!the_queue.empty()) { popped_value = move(the_queue.front()); the_queue.pop(); isWaited = true; break; } if (m_bStopWaiting) { break; } } } m_bStopWaiting = false; return isWaited; } private: bool is_not_empty() { return !the_queue.empty(); } queue<Data> the_queue; mutable mutex the_mutex; condition_variable the_condition; bool m_bStopWaiting; }; #endif
06-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值