繁体   English   中英

理解这个函数 c++

[英]understanding this function c++

我在函数下面有这个 c++ 函数,它使用第一个和最后一个索引,并检查以下数字是否大于或小于下一个索引。 如果是,则将 x 或 y 变量替换为当前索引的值。

这是功能:

template<class Type>
void funcExp(Type list[], int size) {
    Type x = list[0];
    cout << x << endl;
    Type y = list[size - 1];
    cout << y << endl;
    for(int j = 1; j < size; j++) {
        if(x < list[j]) x = list[j];

        if(y > list[size - 1 - j]) y = list[size - 1 - j];
    }
    cout << x << endl;
    cout << y << endl;
}

在我的主要我有这个:

int list[10] = {5,3,2,10,4,19,45,13,61,11};
funcExp(List, 10);

我了解该代码如何处理数字,但我不确定该代码如何处理字符串。 例如:

string strList[] = {"One", "Hello", "Four", "Three", "How", "Six"}; 
funcExp(strList, 6);

返回以下输出:

x = three 
y = four

我认为它正在计算每个字符,但我得到了不同的输出。 我的问题是,这个函数如何处理字符串数组。

此函数通过始终保留比较中“获胜”的值来查找数组中的最大值 ( x ) 和最小值 ( y ) 元素。

比较是使用默认规则进行的(除非您重载了运算符),即整数的普通数字比较和字符串的字母顺序。


请注意,没有理由执行从左到右和从右到左的搜索之一。 下面的代码会更有效率:

template<class Type>
void funcExp(Type list[], int size) {
    Type x = list[0];
    cout << x << endl;
    Type y = list[0];
    cout << y << endl;
    for(int j = 1; j < size; j++) {
        if(x < list[j]) x = list[j];

        else if(y > list[j]) y = list[j];
    }
    cout << x << endl;
    cout << y << endl;
}

通过依次比较字母来比较字符串,直到找到差异为止。

“四”以“F”开头,它比您单词的任何其他首字母都要小

“三”以“T”开头,它比您单词的任何其他首字母都大

这与std::lexicographical_compare过程相同

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM