如何在不使用min_element C++的情况下找到向量中的最小值和最大值<double>
How to find the min and max in a vector<double> without using min_element C++
我有一个向量,它包含用户输入的多少元素。如果用户输入4倍,将有4个;等。
我是C 编程的新手,我正在尝试通过迭代每个元素并确定向量中的最小值和最大双重的方法来弄清楚如何使用循环的方法。我很困惑,因为由于我们不知道向量的长度是多少,所以我不确定如何解决这个问题。我想从矢量中找到最大/分钟及其索引是什么。
vector<double> numbers;
double n;
std::cout << "Enter in numbers :";
std::getline(std::cin, n);
numbers.push_back(n);
size_t iMax=0,iMin=0;
for(size_t i=1; i<x.size(); ++i)
{
if(x[iMax] < x[i])
iMax=i;
if(x[iMin] > x[i])
iMin=i;
}
//iMax is index of the biggest num in the array
您可以使用std::set<double>
。
std::set<double> numbers;
double minValue = *numbers.begin();
double maxValue = *numbers.rbegin();
未经测试,但这应该在您的向量中找到最大值。
int max = 0;
if (!numbers.isEmpty())
max = numbers[0]; //if its not empty, start it at the first element.
//this ensures that your max is never HIGHER
//than the largest element
for(int i = 0; i < numbers.size(); i++) {
if(numbers[i] > max)
max = numbers[i]; //replace the old max if the current element is higher
}
如果您使用的是C 11,还有另一个更简单的解决方案:
double max(vector<double> n)
{
double max = n[0] ;
for(double i : n)
if(i > max)
max = i ;
return max ;
}
参考:http://www.cprogramming.com/c 11/c 11-ranged-for-loop.html
使用vector<double>::iterator
类型的迭代器。然后,您可以将指针添加到通过向量的迭代中,直到您达到vector.end()(位于向量的最后一个元素之后))。
double max(vector<double> n)
{
double max = n[0] ;
vector<double>::iterator iter ;
for(iter = n.begin() ; iter != n.end() ; iter++)
if(*iter > max)
max = *iter ;
return max ;
}
让我知道您是否有任何疑问。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- EASTL矢量<向量<int>>连续的
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 将图像加载到Mat-vvector<向量<垫子>>