#include <iostream>
#include<iomanip>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
if (n != 0)
{
int nn = n;
vector<int>a;
while (nn--)
{
int x;
cin >> x;
a.push_back(x);//生成数组
}
vector<int>::iterator mp= min_element(a.begin(), a.end());
int minp = distance(a.begin(), mp);//这里是找到最小值的下标
int t;
t = a[minp];
a[minp] = a[0];
a[0] = t;//交换
for (int i = 0; i < n - 1; i++)
{
cout << a[i] << " ";
}
cout << a[n - 1] << endl;
}
}
return 0;
}
主要学习了查找数组最大最小值下表的函数min_element()用法如下
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> a = { 2,4,6,7,1,0,8,9,6,3,2 };
auto maxPosition = max_element(a.begin(), a.end());
cout << *maxPosition << " at the postion of " << maxPosition - a.begin() <<endl;
//cout << a[maxPosition - a.begin()] << " at the postion of " << distance(a.begin(), maxPosition) << endl;
system("pause");
return 0;
}
#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
std::vector<double>::iterator biggest = std::max_element(std::begin(v), std::end(v));
//or std::vector<double>::iterator biggest = std::max_element(v.begin(), v.end);
std::cout << "Max element is " << *biggest<< " at position " <<std::distance(std::begin(v), biggest) << std::endl;
//另一方面,取最大位置也可以这样来写:
//int nPos = (int)(std::max_element(v.begin(), v.end()) - (v.begin());
//效果和采用distance(...)函数效果一致
//说明:max_element(v.begin(), v.end()) 返回的是vector<double>::iterator,
//相当于指针的位置,减去初始指针的位置结果即为最大值得索引。
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest<< " at position " <<std::distance(std::begin(v), smallest) << std::endl;
}
输出:
Max element is 5 at position 4
min element is 1 at position 0