gpt4 book ai didi

c++ - 合并排序的合并操作无法使用 C++ vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:54:36 25 4
gpt4 key购买 nike

#include <iostream>
#include<vector>
std::vector<int> print(std::vector<int> answerVec){
for(int i = 0; i < answerVec.size(); i++){
std::cout<<answerVec.at(i)<<" ";
}
std::cout<<"\n";
return answerVec;
}
std::vector<int> Merge(std::vector<int> left, std::vector<int> right){
int leftSize = left.size();
int rightSize = right.size();
std::vector<int> finalVector;
int leftIterator = 0, rightIterator = 0;
while(leftIterator < leftSize && rightIterator < rightSize){
//std::cout<<"Left"<<left.at(leftIterator)<<"\n";
//std::cout<<"Right"<<right.at(rightIterator)<<"\n";
if((int)left.at(leftIterator) <= (int)right.at(leftIterator)){
finalVector.push_back(left.at(leftIterator));
leftIterator ++;
}
else{
finalVector.push_back(right.at(rightIterator));
rightIterator++;
}
//print(finalVector);
}
while(leftIterator < leftSize){
finalVector.push_back(left.at(leftIterator));
leftIterator ++;
//print(finalVector);
}
while(rightIterator < rightSize){
finalVector.push_back(right.at(rightIterator));
rightIterator++;
//print(finalVector);
}
return finalVector;
}
int main(){
std::vector<int> vecL,vecR,vec;
int n,input;
std::cin>>n;
for(int i = 0; i < n; i++){
std::cin>>input;
vecL.push_back(input);
}
for(int i = 0; i < n; i ++){
std::cin>>input;
vecR.push_back(input);
}
vec = Merge(vecL, vecR);
for(int i = 0; i < vec.size(); i++){
std::cout<<vec.at(i)<<" ";
}
return 0;
}

当我将两个已排序的 vector 作为参数传递时,上面的 Merge 函数无法正常运行。现在已经尝试了一段时间,但无法使其正常工作。评论了我用于调试的一些打印语句。任何帮助将不胜感激。

提前致谢

最佳答案

if((int)left.at(leftIterator) <= (int)right.at(leftIterator)){

这里,第二个leftIterator应该是rightIterator

关于c++ - 合并排序的合并操作无法使用 C++ vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com