[英]My paired vectors are not getting sorted in C++
我已經制作了成對的向量,我想根據另一個向量的值對一個向量進行排序,但是當我運行我的程序時,向量沒有得到排序。 他們只是保持不變。 而且我認為這是因為我制作的這對實際上只是復制了代碼以從互聯網上執行配對排序,並用向量替換了 arrays。
// Sort an array according to other using pair in STL.
// Function to sort vector b according to the order defined by vector a
void pairsort(vector<int> a, vector<int> b, int n)
{
pair<int, int> pairt[n];
// Storing the respective array
// elements in pairs.
for (int i = 0; i < n; i++)
{
pairt[i].first = a[i];
pairt[i].second = b[i];
}
// Sorting the pair array.
sort(pairt, pairt + n);
// Modifying original arrays
for (int i = 0; i < n; i++)
{
a[i] = pairt[i].first;
b[i] = pairt[i].second;
}
}
// Driver function
int main()
{
vector<int> a{60, 100, 120};
vector<int> c{3, 2, 4};
int n = sizeof(c) / sizeof(c[0]);
pairsort(c, a, n);
}
原始向量的副本被傳遞給 arguments vector<int> a
和vector<int> b
。 修改副本不會影響調用者傳遞的內容。
在類型之后添加&
以使它們引用以將 function 中的更改反映給調用者。
還有變長數組,例如pair<int, int> pairt[n];
不在標准 C++ 中。 你應該使用std::vector<pair<int, int> > pairt(n);
反而。
void pairsort(vector<int>& a, vector<int>& b, int n) // make a and be references
{
std::vector<pair<int, int> > pairt(n); // use std::vector instead of non-standard VLA
進行此更改后,這種sort
用法對std::vector
是錯誤的:
sort(pairt, pairt + n);
它應該是:
sort(pairt.begin(), pairt.end());
還有一點是main()
function 中的sizeof(c) / sizeof(c[0])
不是檢索向量中元素數量的正確方法。 它應該被替換為c.size()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.