[英]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.