简体   繁体   中英

what type of data does string.length() reutrn in c++?

I am a beginner in C++. Today, I was trying to solve problem 139 on Leetcode, here is the pseudo-code:

for (string& word: wordDict) {
    int i=0;
    int word_len = word.length();
    cout << i - word.length() << endl;
    cout << i - word_len << endl;
}

And here is the result:

18446744073709551611
-5
18446744073709551613
-3

Why does the integer seem out of range if I don't declare the type of word.length() in front?

The type of the member function length is an unsigned integer type named like size_type .

As the type is unsigned then the expression

i - word.length()

also has an unsigned value because the rank of the type size_type (that usually corresponds to the type size_t) is not less than the rank of the type int.

You could write for example

i - ( int )word.length()

to use signed arithmetic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM