合并2个不同长度的矢量并预先对它们进行排序而不使用sort函数

时间:2018-02-25 22:52:03

标签: c++ sorting

到目前为止,这是我的代码。一切都有效,但排序和合并。如何在不使用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);
}

1 个答案:

答案 0 :(得分:0)

要解决超出范围的错误,只需将for循环更改为下面的错误,以确保que1countque2count永远不会超过其字符串大小:

for (int i = 0; i < (que1.size() + que2.size()) && que2count < que2.size() && que1count < que1.size(); ++i)

现在这将编译。但是,您的合并循环仍然无法实现您的目的。尝试使用que1que2的一些向量功能。您现在只使用queMerge的矢量功能。

这可能会有所帮助:http://www.cplusplus.com/forum/beginner/98971/