矢量C++的指数/最大值/最小值<double>
Index/Max/Min of a Vector<double> C++
我希望能够找出向量中的最高和最低元素,并找出当前高/低数字的位置/索引。例如,
vector<double> x;
std::cout << "Enter in #s: ";
double numbers;
std::getline(std::cin, numbers);
x.push_back(numbers);
假设用户输入的4.3 1.0 2.99 43.5
我希望结果说
The highest number is 43.5 at position 4
The lowest number is 1.0 at position 2
我想知道是否有任何方法可以在不使用MIN_ELEMENT/MAX_ELEMENT函数的情况下实现此代码,并使用for loop?
进行操作?我想使用以下内容:
for (int i=0;i < x.size();i++)
if ( //the number is less than ) {
std::cout << "The lowest number is...... at position .....";
if ( //the number is greather than ) {
std::cout << "The highest number is......at position......";
将每个数字与到目前为止找到的最大最大/分钟进行比较。
如果它更大/较小,则用它更换最大/分钟,并记下索引
您需要一个最大和最小变量和两个索引 - 如果最大和最小为
为此,您需要存储最高和最低元素的索引,并将它们与每个迭代的当前元素进行比较。
// Note: the below code assumes that the container (vector) is not empty
// you SHOULD check if the vector contains some elements before executing the code below
int hi, lo; // These are indices pointing to the highest and lowest elements
hi = lo = 0; // Set hi and lo to the first element's index
// Then compare the elements indexed by hi and lo with the rest of the elements
for (int i = 1;i < x.size();i++) {
if(x[i] < x[lo]) {
// The element indexed by i is less than the element indexed by lo
// so set the index of the current lowest element to i
lo = i;
}
// Below, else if is used and not if because the conditions cannot be both true
else if(x[i] > x[hi]) {
// Same logic as the above, only for the highest element
hi = i;
}
}
// Note: the position indicated by the output below will be 0-based
std::cout << "The lowest number is " << x[lo] << " at position " << lo << ".n";
std::cout << "The highest number is " << x[hi] << " at position " << hi << ".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
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- C++在数学计算中将double转换为int
- 在c++中为double类型的数组创建一个unique_ptr
- vector<vector<double>> to mxArray using memcpy
- (double) 和 double() 之间的区别
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- C++ Version Of Double.longBitsToDouble
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- 为什么 nlohmann/json 序列化 "null" 而不是在 double 上"0"?
- 使用 std::vector<double> 访问由 std::unique_ptr<double[2] 管理的数据>
- 将 std::vector<double> 从 C++ 包装到 C 以在 Swift 中使用
- 错误:无法将"<lambda(double)>"转换为"double(*)(double)"
- 如何正确将"strings"转换为"double"?
- 如何在<double>矢量中创建复杂类型的模板<T>?
- "double* grade"、"double *grade"和"double* fn()"有什么区别?
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ