之前說過,記得給變量初始化。
今天突然想到了一個問題,如果聲明了一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!
~~~
- 前言
- deprecated關鍵字
- 指針(內存泄露)
- 頭文件相互包含(Compiler error C2653: not a class or namespace name)
- 獲取一張圖片的width和height
- This function or variable may be unsafe.
- 智能指針陷阱
- string中的c_str()陷阱
- wstring與string的轉換
- windows下chrome瀏覽器插件不能安裝
- 重定義關鍵字
- 正確釋放vector的內存
- 獲取設備環境HDC
- 抽象類不能實例化對象(但是你明明定義的不是抽象類)
- 重載賦值運算符的自我賦值
- 程序中的變量未初始化
- 成對使用new和delete時要采取相同的形式
- 意想不到的除數為零
- map的初始化(插入數據)
- 正則表達式截取字符串
- 捕獲窗口之外的鼠標消息(鉤子還是??)
- 類中的靜態成員變量(static or const static)
- 有if就要有else(一定成對)
- map查找結果處理
- 使用using namespace std的壞習慣
- new一個指針數組、以及創建動態二維數組
- 使用太多的全局變量
- 沒有及時break出for循環
- vector使用erase后迭代器變成野指針
- C++函數的默認參數(重新定義默認參數)
- 0xC0000005: 讀取位置 xxx時發生訪問沖突
- std::string初始化、最快速判斷字符串為空
- 你開發的軟件安裝在C盤Program Files (x86)下產生的異常