首页 \ 问答 \ C ++字符串。(C++ string. why is the answer showing that string “dog” is greater than “cat”, then “cat” is greater than “dog”?)

C ++字符串。(C++ string. why is the answer showing that string “dog” is greater than “cat”, then “cat” is greater than “dog”?)

我不太确定为什么大字符串(“猫”和“狗”)的答案不一致。 我正在做一些链接列表和使用模板的事情。 我的好奇心让我修改模板和函数重载。 如果任何人都可以解释发生了什么,我将不胜感激。 谢谢。

#include <iostream>
using namespace std;   // for the sake of simplicity. (otherwise, std::)

// Function overloading and the use of templates

// overloading the function larger
int larger(int, int);
char larger(char, char);
double larger(double, double);
string larger(string, string);

template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2);


int main() {

    cout << endl;
    cout << "Function Overloading" << endl;

    cout << "larger(15, 27)            =  " << larger(15, 27) << endl;
    cout << "larger('X', 'P')          =  " << larger('X', 'P') << endl;
    cout << "larger(4.9, 3.2)          =  " << larger(4.9, 3.2) << endl;
    cout << "larger(cat, dog)          =  " << larger("cat", "dog") << endl;

    cout << endl;
    cout << "Using the function template to find the larger of two items" << endl;
    cout << "anyLarger(15, 27)         =  " << anyLarger(15, 27) << endl;
    cout << "anyLarger('X', 'P')       =  " << anyLarger('X', 'P') << endl;
    cout << "anyLarger(4.9, 3.2)       =  " << anyLarger(4.9, 3.2) << endl;
    cout << "anyLarger(cat, dog)       =  " << anyLarger("cat", "dog") << endl;
    cout << endl;


    cout << "Compare two strings:   cat, dog" << endl;
    if ("cat" >= "dog") {
      cout << "cat is greater than dog" << endl;
    }
    else {
      cout << "dog is greater than cat" << endl;
    }

    cout << endl;
    string strCat = "cat";
    string strDog = "dog";
    cout << "string strCat = cat" << endl;
    cout << "string strDog = dog" << endl;
    if (strCat >= strDog) {
      cout << "strCat is greater than strDog" << endl;
    }
    else {
      cout << "strDog is greater than strCat" << endl;
    }
    cout << endl;
} // end main 

// Overloading larger
int larger(int x, int y) {
    if (x >= y)
      return x;
    else 
      return y;
}

char larger(char a, char b) {
    if (a >= b)
      return a;
    else 
      return b;
}

double larger(double p, double q) {
    if (p >= q)
      return p;
    else
      return q;
}

string larger(string y, string z) {
    if (y >= z)
      return y;
    else
      return z;
}


// Defining the template function
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2)
{
    if (parameter1 >= parameter2)
      return parameter1; 
    else
      return parameter2;
}

这是运行程序后的结果。

Function Overloading
larger(15, 27)            =  27
larger('X', 'P')          =  X
larger(4.9, 3.2)          =  4.9
larger(cat, dog)          =  dog

Using the function template to find the larger of two items
anyLarger(15, 27)         =  27
anyLarger('X', 'P')       =  X
anyLarger(4.9, 3.2)       =  4.9
anyLarger(cat, dog)       =  cat

Compare two strings:   cat, dog
cat is greater than dog

string strCat = cat
string strDog = dog
strDog is greater than strCat

==============================================

更新:进行了一些更改并使用了strcmp

#include <iostream>
#include <string.h>
using namespace std;

// Function overloading and the use of templates


// overloading the function larger
int larger(int, int);
char larger(char, char);
double larger(double, double);
string larger(string, string);


template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2);


int main(){

  cout << endl;
  cout << "// Function Overloading" << endl;


  cout << "larger(15, 27)              =  " << larger(15, 27) << endl;
  cout << "larger('X', 'P')            =  " << larger('X', 'P') << endl;
  cout << "larger(4.9, 3.2)            =  " << larger(4.9, 3.2) << endl;
  cout << "larger(\"cat\", \"dog\")        =  " << larger("cat", "dog") << endl;

  cout << endl;
  cout << "// Using the function template to find the larger of two items" << endl;
  cout << "anyLarger(15, 27)           =  " << anyLarger(15, 27) << endl;
  cout << "anyLarger('X', 'P')         =  " << anyLarger('X', 'P') << endl;
  cout << "anyLarger(4.9, 3.2)         =  " << anyLarger(4.9, 3.2) << endl;
  cout << "anyLarger(\"cat\", \"dog\")     =  " << anyLarger("cat", "dog") << endl;
  cout << endl;


  cout << "// Compare two strings using >= :   \"cat\", \"dog\"" << endl;
  if ("cat" >= "dog") {
    cout << "\"cat\" is greater than \"dog\"" << endl;
  }
  else {
    cout << "\"dog\" is greater than \"cat\"" << endl;
  }

  cout << endl;
  cout << "// The use of variables: strCat and strDog. Compare using >=" << endl;
  string strCat = "cat";
  string strDog = "dog";
  cout << "string strCat = \"cat\";" << endl;
  cout << "string strDog = \"dog\";" << endl;
  if (strCat >= strDog) {
    cout << "strCat is greater than strDog" << endl;
  }
  else {
    cout << "strDog is greater than strCat" << endl;
  }
  cout << endl;


  cout << "// Using strcmp.   strcmp(\"cat\", \"dog\")" << endl; 
  int result = strcmp("cat", "dog");
  if (result > 0) {
    cout << "\"cat\" is greater than \"dog\"" << endl;
  }
  else {
    cout << "\"dog\" is greater than \"cat\"" << endl;
  }
}

// Overloading larger
int larger(int x, int y) {
if (x >= y)
    return x;
  else 
    return y;
}


char larger(char a, char b) {
  if (a >= b)
    return a;
  else 
    return b;
}


double larger(double p, double q) {
  if (p >= q)
    return p;
  else
    return q;
}

string larger(string y, string z) {
  if (y >= z)
    return y;
  else
    return z;
}


// Defining the template function
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2)
{
  if (parameter1 >= parameter2)
    return parameter1; 
  else
    return parameter2;
}

================

更新:输出

// Function Overloading
larger(15, 27)              =  27
larger('X', 'P')            =  X
larger(4.9, 3.2)            =  4.9
larger("cat", "dog")        =  dog

// Using the function template to find the larger of two items
anyLarger(15, 27)           =  27
anyLarger('X', 'P')         =  X
anyLarger(4.9, 3.2)         =  4.9
anyLarger("cat", "dog")     =  cat

// Compare two strings using >= :   "cat", "dog"
"cat" is greater than "dog"

// The use of variables: strCat and strDog. Compare using >=
string strCat = "cat";
string strDog = "dog";
strDog is greater than strCat

// Using strcmp.   strcmp("cat", "dog")
"dog" is greater than "cat"

I'm not quite sure why the answer for the larger string ("cat" and "dog") is not consistent. I was doing some things with Linked Lists and the use of templates. My curiosity got me to revise templates and function overloading. If anyone can explain what is going on, I would appreciate it. Thank you.

#include <iostream>
using namespace std;   // for the sake of simplicity. (otherwise, std::)

// Function overloading and the use of templates

// overloading the function larger
int larger(int, int);
char larger(char, char);
double larger(double, double);
string larger(string, string);

template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2);


int main() {

    cout << endl;
    cout << "Function Overloading" << endl;

    cout << "larger(15, 27)            =  " << larger(15, 27) << endl;
    cout << "larger('X', 'P')          =  " << larger('X', 'P') << endl;
    cout << "larger(4.9, 3.2)          =  " << larger(4.9, 3.2) << endl;
    cout << "larger(cat, dog)          =  " << larger("cat", "dog") << endl;

    cout << endl;
    cout << "Using the function template to find the larger of two items" << endl;
    cout << "anyLarger(15, 27)         =  " << anyLarger(15, 27) << endl;
    cout << "anyLarger('X', 'P')       =  " << anyLarger('X', 'P') << endl;
    cout << "anyLarger(4.9, 3.2)       =  " << anyLarger(4.9, 3.2) << endl;
    cout << "anyLarger(cat, dog)       =  " << anyLarger("cat", "dog") << endl;
    cout << endl;


    cout << "Compare two strings:   cat, dog" << endl;
    if ("cat" >= "dog") {
      cout << "cat is greater than dog" << endl;
    }
    else {
      cout << "dog is greater than cat" << endl;
    }

    cout << endl;
    string strCat = "cat";
    string strDog = "dog";
    cout << "string strCat = cat" << endl;
    cout << "string strDog = dog" << endl;
    if (strCat >= strDog) {
      cout << "strCat is greater than strDog" << endl;
    }
    else {
      cout << "strDog is greater than strCat" << endl;
    }
    cout << endl;
} // end main 

// Overloading larger
int larger(int x, int y) {
    if (x >= y)
      return x;
    else 
      return y;
}

char larger(char a, char b) {
    if (a >= b)
      return a;
    else 
      return b;
}

double larger(double p, double q) {
    if (p >= q)
      return p;
    else
      return q;
}

string larger(string y, string z) {
    if (y >= z)
      return y;
    else
      return z;
}


// Defining the template function
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2)
{
    if (parameter1 >= parameter2)
      return parameter1; 
    else
      return parameter2;
}

Here is the result after running the program.

Function Overloading
larger(15, 27)            =  27
larger('X', 'P')          =  X
larger(4.9, 3.2)          =  4.9
larger(cat, dog)          =  dog

Using the function template to find the larger of two items
anyLarger(15, 27)         =  27
anyLarger('X', 'P')       =  X
anyLarger(4.9, 3.2)       =  4.9
anyLarger(cat, dog)       =  cat

Compare two strings:   cat, dog
cat is greater than dog

string strCat = cat
string strDog = dog
strDog is greater than strCat

==============================================

Update: Made some changes and used strcmp

#include <iostream>
#include <string.h>
using namespace std;

// Function overloading and the use of templates


// overloading the function larger
int larger(int, int);
char larger(char, char);
double larger(double, double);
string larger(string, string);


template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2);


int main(){

  cout << endl;
  cout << "// Function Overloading" << endl;


  cout << "larger(15, 27)              =  " << larger(15, 27) << endl;
  cout << "larger('X', 'P')            =  " << larger('X', 'P') << endl;
  cout << "larger(4.9, 3.2)            =  " << larger(4.9, 3.2) << endl;
  cout << "larger(\"cat\", \"dog\")        =  " << larger("cat", "dog") << endl;

  cout << endl;
  cout << "// Using the function template to find the larger of two items" << endl;
  cout << "anyLarger(15, 27)           =  " << anyLarger(15, 27) << endl;
  cout << "anyLarger('X', 'P')         =  " << anyLarger('X', 'P') << endl;
  cout << "anyLarger(4.9, 3.2)         =  " << anyLarger(4.9, 3.2) << endl;
  cout << "anyLarger(\"cat\", \"dog\")     =  " << anyLarger("cat", "dog") << endl;
  cout << endl;


  cout << "// Compare two strings using >= :   \"cat\", \"dog\"" << endl;
  if ("cat" >= "dog") {
    cout << "\"cat\" is greater than \"dog\"" << endl;
  }
  else {
    cout << "\"dog\" is greater than \"cat\"" << endl;
  }

  cout << endl;
  cout << "// The use of variables: strCat and strDog. Compare using >=" << endl;
  string strCat = "cat";
  string strDog = "dog";
  cout << "string strCat = \"cat\";" << endl;
  cout << "string strDog = \"dog\";" << endl;
  if (strCat >= strDog) {
    cout << "strCat is greater than strDog" << endl;
  }
  else {
    cout << "strDog is greater than strCat" << endl;
  }
  cout << endl;


  cout << "// Using strcmp.   strcmp(\"cat\", \"dog\")" << endl; 
  int result = strcmp("cat", "dog");
  if (result > 0) {
    cout << "\"cat\" is greater than \"dog\"" << endl;
  }
  else {
    cout << "\"dog\" is greater than \"cat\"" << endl;
  }
}

// Overloading larger
int larger(int x, int y) {
if (x >= y)
    return x;
  else 
    return y;
}


char larger(char a, char b) {
  if (a >= b)
    return a;
  else 
    return b;
}


double larger(double p, double q) {
  if (p >= q)
    return p;
  else
    return q;
}

string larger(string y, string z) {
  if (y >= z)
    return y;
  else
    return z;
}


// Defining the template function
template <class elementType>
elementType anyLarger(elementType parameter1, elementType parameter2)
{
  if (parameter1 >= parameter2)
    return parameter1; 
  else
    return parameter2;
}

================

Update: Output

// Function Overloading
larger(15, 27)              =  27
larger('X', 'P')            =  X
larger(4.9, 3.2)            =  4.9
larger("cat", "dog")        =  dog

// Using the function template to find the larger of two items
anyLarger(15, 27)           =  27
anyLarger('X', 'P')         =  X
anyLarger(4.9, 3.2)         =  4.9
anyLarger("cat", "dog")     =  cat

// Compare two strings using >= :   "cat", "dog"
"cat" is greater than "dog"

// The use of variables: strCat and strDog. Compare using >=
string strCat = "cat";
string strDog = "dog";
strDog is greater than strCat

// Using strcmp.   strcmp("cat", "dog")
"dog" is greater than "cat"

原文:https://stackoverflow.com/questions/34232689
更新时间:2022-08-19 21:08

最满意答案

如果[H|T]匹配[]H=T=[] ,那么使用模式匹配[[]]不能与[]区分。

此外,patterns [][H|T]不再相互排斥,所以如果在递归函数中首先意外地匹配[H|T] ,其中[]是基本情况,则会导致无限递归。

同样使用[]作为“这个列表没有头”的符号似乎很随意,可能会让很多用户感到惊讶。


If [H|T] would match [] with H=T=[], then [[]] would not be distinguishable from [] using pattern matching.

Further the patterns [] and [H|T] would no longer be mutually exclusive, so if you accidentally matched [H|T] first in a recursive function, where [] is the base case, you'd cause infinite recursion.

Also using [] as a symbol for "this list does not have a head" seems quite arbitrary and might surprise a lot of users.

相关问答

更多
  • 其规则在Scala语言规范的8.5节“模式匹配匿名函数”中定义。 如果使用模式匹配的匿名函数,则必须部分提供类型。 你可以这样说,类型是(Double, Double) => Double ,这是Function2[Double, Double, Double]简写形式。 现在: 如果期望的类型是scala.Function k [ S 1 ,…, S k , R ] ,表达式被认为等同于匿名函数: (x1:S1,…,xk:Sk) => (x1,…,xk) match { case p1 => b1 … ...
  • ([, ]+)表示“匹配一个或多个逗号和/或空格并将它们作为一组捕获”,因此在第二个示例中,您将看到在一个组中返回的整个分隔符字符串。 ([, ])+表示“匹配一个逗号或空格,并捕获一组或多组这些”。 所以在你的第三个例子中,每个分隔符都被捕获在它自己的组中,而你每次只获得最后一个。 ([, ]+) says "match one or more commas and/or spaces and capture them as a group", thus in your second example yo ...
  • 其实呢他们根本上是截然不同的! 至少在Haskell,无论如何。 卫兵既简单又灵活:它们本质上只是一些特殊的语法,转化为一系列if / then表达式。 你可以在守卫中放置任意的布尔表达式,但是他们不会做任何你不能用常规的if来做任何事情。 模式匹配做了几个额外的事情:它们是解构数据的唯一方法 ,并且它们在其范围内绑定标识符 。 在同样的意义上,守卫等同于表达式,模式匹配等效于表达式。 声明(顶级或类似let表达式)也是一种模式匹配的形式,“正常”定义是与简单模式匹配的唯一标识符。 模式匹配也往往是Hask ...
  • 你错过了正斜杠/ ,试试这个: /section/([A-Za-z0-9\/-]+) Regex101演示 You missed the forward slash /, try this: /section/([A-Za-z0-9\/-]+) Regex101 Demo
  • 你可能想要的不是返回一个值(forall a . a)因为它在几个方面是错误的。 首先,你没有任何价值,而只是两个中的一个。 对于二,这种类型不能存在于行为良好的程序中:它对应于无限循环和异常的类型,例如底部。 最后,这种类型允许拥有它的人做出选择以更具体地实例化它。 因为你将它交给你的函数调用者,这意味着他们可以选择你拥有的Int或Char中的哪一个。 显然这没有意义。 相反,你最想要的是向你的功能用户提出要求:“无论这种类型是什么,你都必须工作”。 foo :: (forall a . a -> r) ...
  • 如果没有matches或find则group抛出IllegalStateException 。 在调用group之前调用matches ,以使表达式与完整的String匹配: class NumberTest { final static Pattern pattern = Pattern.compile("R(\\d+)"); public static void main(String[] args) { System.out.println(new NumberTes ...
  • 不,这不会提高性能。 在这两种情况下,编译器都必须评估WHNF的参数来检查它是否为空列表。 实际上,这个函数很可能会在编译过程中被重写,而生成的代码完全不同于您编写的代码(假设您使用优化进行编译)。 查看生成的核心( 无需优化编译): (letrec { f1_aLn [Occ=LoopBreaker] :: [Integer] -> Integer [LclId, Arity=1, Str=DmdType] f1_aLn = \ (ds_d1gX :: [Integer]) - ...
  • 如果[H|T]匹配[]与H=T=[] ,那么使用模式匹配[[]]不能与[]区分。 此外,patterns []和[H|T]不再相互排斥,所以如果在递归函数中首先意外地匹配[H|T] ,其中[]是基本情况,则会导致无限递归。 同样使用[]作为“这个列表没有头”的符号似乎很随意,可能会让很多用户感到惊讶。 If [H|T] would match [] with H=T=[], then [[]] would not be distinguishable from [] using pattern matchi ...
  • when警卫引用单个案例时,不管有多少个模式组合在一起。 案件需要分开: let foo = function | Some (0, x) when x > 0 -> "bar" | None -> "bar" | _ -> "baz" 出于这个原因,将返回值分解可能会更好,因此不会重复可能的复杂表达式: let foo value = let ret = "bar" match value with | Some (0, x) when x > 0 -> ret | None ...
  • 您可以使用when将模式与布尔条件一起使用: let check n = function | x when x = n -> true | _ -> false 但是,这不是很特别:它只是使用if不同语法。 OCaml不支持任何类型的“动态”模式,使您可以匹配变量的值 - 模式都是静态的。 有一种名为bondi的研究语言,它支持这样的动态模式。 它与OCaml非常相似,所以如果你对这种功能感兴趣,你应该玩它。 You can use when to have patterns along with bo ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)