首页 > 解决方案 > 我的配对向量没有在 C++ 中排序

问题描述

我已经制作了成对的向量,我想根据另一个向量的值对一个向量进行排序,但是当我运行我的程序时,向量没有得到排序。他们只是保持不变。而且我认为这是因为我制作的这对实际上只是复制了代码以从互联网上执行配对排序,并用向量替换了数组。

// 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);
}

标签: c++sortingvectorstdstd-pair

解决方案


原始向量的副本被传递给参数vector<int> avector<int> b。修改副本不会影响调用者传递的内容。

在类型之后添加&以使它们引用以将函数中的更改反映给调用者。

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());

还有一点是,sizeof(c) / sizeof(c[0])main()函数中检索向量中元素的数量不是正确的方法。它应该替换为c.size().


推荐阅读