1.比较string对象大小可以直接用逻辑运算符 >、<等比较,很方便
注意:string对象比较大小是按位比较,比如123小于321,abc小于cba
代码如下:
#include<iostream>
#include<string>
#include<cctype>
#include<iterator>
#include<vector>
#include<cstddef>
using namespace std;
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
//cout << s1 << s2 << endl;
//cout<<s1<<" "<<s2<<endl;
if (s1 > s2)
{
cout << "s1比s2大" << endl;
}
else if (s1 < s2)
{
cout << "s1比s2小" << endl;
}
else if (s1 == s2)
{
cout << "s1与s2相等" << endl;
}
}
return 0;
}
2.比较vector对象大小也可以直接用逻辑运算符 >、<等比较,很方便
注意:vector对象比较大小是按位比较,比如123小于321,abc小于cba
int word1, word2;
vector<int> text1, text2;
while (cin >> word1 >> word2)
{
text1.push_back(word1);
text2.push_back(word2);
}
if (text1 > text2)
{
cout << "第一个向量大于第二个" << endl;
}
else if (text1 < text2)
{
cout << "第一个向量小于第二个" << endl;
}
else if (text1 == text2)
{
cout << "两个向量相等" << endl;
}
return 0;
3.但是,数组比较大小和string、vector有所不同,数组比较大小用到了指针(迭代器)
int a[] = { 0,21,22,1213,21,11,21,2,1 };
//int b[] = { 121,13,1111,11,1,11,1 };
int b[] = { 0,21,22,1213,21,11,21,2,90 };
if (size(a) != size(b))
{
cout << "两个数组不等" << endl;
return false;
}
if (size(a) == size(b))
{
for (int* p = begin(a), *q = begin(b); p != end(a) && q != end(b); ++p, ++q)
{
if (*p > *q)
{
cout << "第一个数组大于第二个" << endl;
return true;
}
if (*p < *q)
{
cout << "第一个数组小于第二个" << endl;
return true;
}
//return true;
}
cout << "两个数组相等" << endl;
return true;
仅供参考!!!!!