C++:string、vector、数组之比较两个或多个对象的不同点,代码说明

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;

仅供参考!!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值