2014-01-17 39 views
3

我寫了一個程序,它使用find_last_of方法找到字符串中的一個字符。不同大小的std :: string :: npos

// ... 
unsigned found; 
found = name.find_last_of(character); 
if (found == std::string::npos) { 
    std::cout << "NOT FOUND" << std::endl; 
} 
// ... 

我已經在兩臺機器上編譯了代碼,它只在其中一個機器上工作(PC1)。我調試過它並發現,std :: string :: npos對於PC1和PC2是不同的。

如果沒有找到字符,那麼find_last_of == 4294967295爲兩臺機器返回的值。

PC1:

std::string::npos == 4294967295 

PC2:

std::string::npos == 18446744073709551615 

一些測試:

PC1:

sizeof(size_t) == 4 

PC2:

sizeof(size_t) == 8 

第一臺機器使用的是32位操作系統,第二臺機器是64位操作系統。

我應該使用什麼來比較find_last_of方法返回的值以使它在兩臺機器上都能正常工作?

+0

爲什麼它不工作? –

+2

將它與'std :: string :: npos'進行比較。 – juanchopanza

+0

@LuchianGrigore如果'found',即'unsigned'的類型太小而不能容納'std :: string :: npos',那麼它將不起作用。 – hvd

回答

8

我應該用什麼來比較find_last_of 方法返回的值,以使它在兩臺機器上都能正常工作?

std::string::npos,並且位置(found)的類型應該是size_t

常量的具體大小在不同的體系結構上可能不同,但這並不是你的擔心。

npos是一個靜態成員常數值,其值爲size_t類型的元素的最大可能值 。

4

只要看看功能 - http://en.cppreference.com/w/cpp/string/basic_string/find_last_of

SIZE_TYPE find_last_of(常量basic_string的& STR,SIZE_TYPE POS = 0)常量; (1)
size_type find_last_of(const CharT * s,size_type pos,size_type count)const; (2)
size_type find_last_of(const CharT * s,size_type pos = 0)const; (3)
size_type find_last_of(CharT ch,size_type pos = 0)const; (4)

顯然,std::string::size_type是適當的類型來存儲在,之後比較std::string::npos將工作返回值。

+0

只是爲了澄清,這與其他答案並不矛盾。 'std :: string :: size_type'和'size_t'是相同的類型。儘管'size_type'更通用,並且在其他情況下也適用,其中'(...):: size_type'不是'size_t'。 – hvd

相關問題