我的配对向量没有在 C++ 中排序
My paired vectors are not getting sorted in 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);
}
原始向量的 副本 被传递给参数 vector<int> a
和 vector<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());
还有一点是 main()
函数中的 sizeof(c) / sizeof(c[0])
不是检索向量中元素数量的正确方法。它应该被替换为 c.size()
.
我已经制作了成对的向量,我想根据另一个向量的值对一个向量进行排序,但是当我 运行 我的程序时,向量没有得到排序。他们只是保持不变。而且我认为这是因为我所做的配对我实际上只是从互联网上复制了代码来执行配对排序并将数组替换为向量。
// 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);
}
副本 被传递给参数 vector<int> a
和 vector<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());
还有一点是 main()
函数中的 sizeof(c) / sizeof(c[0])
不是检索向量中元素数量的正确方法。它应该被替换为 c.size()
.