對于使用串列向量的 BucketSort 程式。我使用 std::max_element 從向量中找出最大元素。
但是看起來一旦原始向量被清除和更新,max_element 回傳的迭代器也會將值更改為來自同一索引的向量(vList)的更新值。
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;
void BucketSort(std::vector<int>& vList)
{
int i = 0;
auto maxElem = std::max_element(vList.begin(), vList.end());
std::vector<std::list<int>> tempList;
std::cout << "Max element = " << *maxElem << "\n";
for (i = 0; i <= *maxElem; i )
tempList.push_back({});
for (auto x : vList)
{
tempList[x].push_back(x);
}
vList.clear();
std::cout << "*max = " << *maxElem << "\n";
i = 0;
while(i <= *maxElem)
{
std::cout << "*max = " << *maxElem << " i = " << i << " tempList[i].size() = " << tempList[i].size() << "\n";
if (tempList[i].empty() == false)
{
vList.push_back(tempList[i].front());
tempList[i].pop_front();
}
else
i ;
}
}
int main()
{
std::vector<int> vList = {1, 5, 4, 1 };
BucketSort(vList);
return 0;
}
產生以下輸出
Max element = 5
*max = 5
*max = 5 i = 0 tempList[i].size() = 0
*max = 5 i = 1 tempList[i].size() = 2
*max = 5 i = 1 tempList[i].size() = 1
*max = 1 i = 1 tempList[i].size() = 0
即使在清除向量后,迭代器是否仍保留對回傳索引的參考?
uj5u.com熱心網友回復:
C 中提供的迭代器存盤了一個被參考的地址。當您清除向量并用新值填充它時,迭代器仍指向同一個位置,并將在該位置顯示新值。看看這個例子:
[0,1,2,3,4]
^
您有一個指向向量的第三個元素的迭代器。現在想象你清除向量并用新值填充它:
[5,6,7,8,9]
^
現在指標指向相同的地址,但該記憶體現在保存了一個新值。您可以通過將資料存盤在區域變數中并在其余代碼中使用它來解決此問題:
int maxValue = *maxElem
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514852.html
標籤:C 算法向量stl迭代器
上一篇:如何檢查數獨中的每個3x3框?
