先决条件:向量,向量对排序
给定一个向量,请跟踪与每个元素相对应的当前索引,并在将打印元素与其先前的相应索引进行排序之后。
例子:
Input: Arr[] = {2, 5, 3, 7, 1}
Output: {1, 4} {2, 0} {3, 2} {5, 1} {7, 3}
Explanation:
Before sorting [index(element)]: [0(2), 1(5), 2(3), 3(7), 4(1)]
After sorting [previous_index(element)]: [4(1), 0(2), 2(3), 1(5), 3(7)]
Input: Arr[] = {4, 5, 10, 8, 3, 11}
Output: {3, 4} {4, 0} {5, 1} {8, 3} {10, 2} {11, 5}
方法:想法是将每个元素及其当前索引存储在向量对中,然后对向量的所有元素进行排序,最后,打印带有索引的元素与之关联。
下面是上述方法的实现:
// C++ implementation to keep track
// of previous indexes
// after sorting a vector
#include
using namespace std;
void sortArr(int arr[], int n)
{
// Vector to store element
// with respective present index
vector > vp;
// Inserting element in pair vector
// to keep track of previous indexes
for (int i = 0; i < n; ++i) {
vp.push_back(make_pair(arr[i], i));
}
// Sorting pair vector
sort(vp.begin(), vp.end());
// Displaying sorted element
// with previous indexes
// corresponding to each element
cout << "Element\t"
<< "index" << endl;
for (int i = 0; i < vp.size(); i++) {
cout << vp[i].first << "\t"
<< vp[i].second << endl;
}
}
// Driver code
int main()
{
int arr[] = { 2, 5, 3, 7, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
sortArr(arr, n);
return 0;
}
输出:
Element index
1 4
2 0
3 2
5 1
7 3
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。