c++ - 我的配对向量没有在 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());
还有一点是,sizeof(c) / sizeof(c[0])
在main()
函数中检索向量中元素的数量不是正确的方法。它应该替换为c.size()
.
推荐阅读
- java - 在循环中仅显示偶数,并添加偶数
- r - 用 NA 替换 COL2 中的行值,其中其他 COL3 值是 R 中的 NA
- python - 多处理代码不产生结果
- c# - 用 new string("...".ToCharArray()) 初始化一个字符串
- sql - 按 id 值计算多个单元格的最佳方法
- c++ - 无法理解 C++ 中的语法错误
- haskell - 模式同义词作为函数的无趣/困惑
- r - 将具有日期时间列的数据框转换为 R 中的时间序列
- bash - golangci-lint 运行命令在 makefile 中显示错误
- android - 如何创建自定义视图充气器并将其设置为样式资源?