没有躲过的坑--std::string初始化、最快速判断字符串为空

之前说过,记得给变量初始化。

今天突然想到了一个问题,如果声明了一std::string类型,怎么初始化呢?

std::string test_string;
std::string test_string_empty = "";
std::string test_string_null = NULL;//运行错误,而非编译错误

简单测试:

#include<iostream>
int main()
{
    std::string test_string;
    std::string test_string_empty = "";
//  std::string test_string_null = NULL;

    if (test_string == "")
    {
        std::cout << "test_string is empty!" << std::endl;
    }

    if (test_string_empty == "")
    {
        std::cout << "test_string_empty is empty!" << std::endl;
    }

    return 0;

}
/*---------------------------------
输出:
test_string is empty!
test_string_empty is empty!
-----------------------------------*/

由此可见,声明一个std::string对象,默认变为空。

更重要的是 std::string不能与null进行比较!!

那么判断一个std::string 为空 是使用empty还是“”呢?

#include<iostream>
int main()
{
    std::string test_string;
    std::string test_string_empty = "";
//  std::string test_string_null = NULL;

    if (test_string == "")
    {
        std::cout << "test_string is empty!" << std::endl;
    }

    if (test_string_empty.empty())
    {
        std::cout << "test_string_empty is empty!" << std::endl;
    }

    if (test_string_empty.length() == 0)
    {
        std::cout << "test_string_empty is empty!" << std::endl;
    }

    return 0;

}
//输出:
//test_string is empty!
//test_string_empty is empty!
//test_string_empty is empty!

三种方法都可以,但是谁更优越呢?

之前搞过一段C Sharp, 犹记得比较长度最快,不知道C++中是不是也是通过长度来判断字符串是否为空的方法最为效率呢。

太晚了,明天继续,欢迎指导:

#include<iostream>
#include <ctime>
#include<Windows.h>
int main()
{
    std::string test_string;
    std::string test_string_empty = "";

    unsigned int ticks1 = 0;
    unsigned int ticks2 = 0;
    unsigned int ticks3 = 0;
    unsigned int ticks4 = 0;
    unsigned int ticks5 = 0;
    unsigned int ticks6 = 0;

    ticks1 = GetTickCount();
    if (test_string_empty == "")
    {
        for (int i = 0; i < 100000; i++)
        {

        }
        ticks2 = GetTickCount();

    }

    ticks3 = GetTickCount();
    if (test_string_empty.empty())
    {
        for (int i = 0; i < 100000; i++)
        {

        }
        ticks4 = GetTickCount();
    }

    ticks5 = GetTickCount();
    if (test_string_empty.length() == 0)
    {
        for (int i = 0; i < 100000; i++)
        {

        }
        ticks6 = GetTickCount();
    }

    std::cout << ticks2 - ticks1 << std::endl;
    std::cout << ticks4 - ticks3 << std::endl;
    std::cout << ticks6 - ticks5 << std::endl;
    return 0;

}

//test_string is empty!
//test_string_empty is empty!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值