[英]Merging 2 vectors of different lengths and sorting them beforehand WITHOUT the sort function
到目前為止,這是我的代碼。 除排序和合並外,其他所有操作均有效。 如何編寫此代碼,使其在合並前進行排序而不使用sort函數?
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector < string > que1;
vector < string > que2;
vector < string > queMerge;
string input;
cout << "Enter queues" << endl;
while(input != "ENDQ"){ //This while loop fills up the first vector with the values until the first "ENDQ" is reached
cin >> input;
que1.push_back(input);
}
que1.pop_back();//This statement removes the "ENDQ" input from the vector changing the vector size to 1 less
input = ""; //Sets input to nothing so that it can loop through the second while loop for the second queue
while(input != "ENDQ"){//This while loop fills up the second vector with the values until the first "ENDQ" is reached
cin >> input;
que2.push_back(input);
}
que2.pop_back();//This statement removes the "ENDQ" input from the vector changing the vector size to 1 less
這是我開始遇到代碼和排序過程問題的地方。
int que1count = 0;
int que2count = 0;
for (int i = 0; i < (que1.size() + que2.size()); ++i) {
if(que2.at(que2count) > que1.at(que1count)){
queMerge.push_back(que2.at(que2count));
que2count++;
}
else{
queMerge.push_back(que1.at(que1count));
que1count++;
}
}
從這里開始的其他所有工作都很好。
cout << "que1: " << que1.size() << endl;
for (int i = 0; i < que1.size(); ++i) {
cout << que1[i] << endl;
}
/*
* The for loop iterates through the first queue and prints out the values indicated at i until the size of the
* queue is reached
*/
cout << endl;
cout << "que2: " << que2.size() << endl;
for (int i = 0; i < que2.size(); ++i) {
cout << que2[i] << endl;
}
/*
* The for loop iterates through the second queue and prints out the values indicated at i until the size of the
* queue is reached
*/
cout << endl;
cout << "queMerge: " << queMerge.size() << endl;
for (int i = 0; i < queMerge.size(); ++i) {
cout << queMerge[i] << endl;
}
/*
* The for loop iterates through the queMerge and prints out the values indicated at i until the size of the
* queue is reached having already been sorted alphabetically earlier in the program
*/
return (0);
}
要解決超出范圍的錯誤,只需將for循環更改為以下內容,以確保que1count
和que2count
不會超過其字符串大小:
for (int i = 0; i < (que1.size() + que2.size()) && que2count < que2.size() && que1count < que1.size(); ++i)
現在將編譯。 但是,您的合並循環仍未達到您的預期目的。 也嘗試對que1
和que2
使用某些矢量功能。 您現在僅對queMerge
使用矢量功能。
這可能會有所幫助: http : //www.cplusplus.com/forum/beginner/98971/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.