【发布时间】:2025-11-27 18:55:01
【问题描述】:
我编写了一个 C++ 程序,目的是快速将一个元素插入一个排序的向量中。它有时有效,但并非一直有效,我无法弄清楚原因。当我用纸和铅笔按照算法进行操作时,它可以解决,但是出了点问题。请帮忙?
#include <time.h>
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
vector<int> sortedVec;
int main() {
// Random seed
srand(time(NULL));
// Put in n random elements
for (int i = 0; i < 10; i++) sortedVec.push_back(rand()%10);
// Sort the vector
bool swapped = true;
int endDecrement = 0;
while (swapped) {
swapped = false;
endDecrement++;
for (int i = 0; i < sortedVec.size()-endDecrement; i++) {
if (sortedVec.at(i) > sortedVec.at(i+1)) {
int swap = sortedVec.at(i);
sortedVec.at(i) = sortedVec.at(i+1);
sortedVec.at(i+1) = swap;
swapped = true;
}
}
}
cout<<"Sorted random list:"<<endl;
for (int i = 0; i < sortedVec.size(); i++) cout<<sortedVec.at(i)<<endl;
int toInsert = rand()%10;
cout<<"Random element to insert = "<<toInsert<<endl;
// Insert a random int to the sorted vector
int minIndex = 0;
int maxIndex = sortedVec.size()-1;
while (true) {
int mid = (maxIndex-minIndex)>>1;
if (toInsert == sortedVec.at(mid) || maxIndex-minIndex < 2) {
sortedVec.insert(sortedVec.begin()+mid, toInsert);
break;
}
else if (toInsert < sortedVec.at(mid)) maxIndex = mid;
else if (toInsert > sortedVec.at(mid)) minIndex = mid;
}
cout<<"Random list with inserted element:"<<endl;
for (int i = 0; i < sortedVec.size(); i++) cout<<sortedVec.at(i)<<endl;
return 0;
}
【问题讨论】:
-
你为什么不使用
std::set来为你排序元素?而事件如果你想使用vector,你可以使用std::sort实现排序,并使用std::equal_range算法找到插入的位置,而不是自己写。 -
如果您打算这样做,是否有理由不使用
std::sort进行排序并使用std::upper_bound查找插入点? (但如果你想按顺序插入,这真的不是最好的方法,IMO)。 -
@Jerry Coffin,这是一个虚拟程序,用于在不同的程序中解决相同的问题。另一个程序执行 A* 搜索并将新节点插入到名为树的向量中。问题是我不知道如何将 std::upper_bound 与 Node 类中的值一起使用(我是 C++ 的新手)。 Node 类有一个名为 fVal 的 int,我想用它来确定插入向量的位置。如果我能得到 std::upper_bound 来检查 tree.at(whatever position).fVal 那就太好了。
-
"a vector named tree" 可能应该是
std::set或std::multiset,具体取决于您的需要 - 尽管我同意,如果您有其他代码假设它是vector,则迁移可以是也很痛。 -
@asimes:是的,你可以这样做——
upper_bound允许你指定一个比较函数/函子。在你的情况下,它的逻辑只是return a.fval < b.fval;