2013-04-08 75 views
0

std :: find未按照我的預期進行評估。std :: find未按預期運行

我有一個向量lexeme_定義爲

static const std::string delimiters_[] = {" ", ",", "(", ")", ";", "=", ".", "*", "-"}; 

static std::vector<std::string> lexeme_(std::begin(delimiters_), std::end(delimiters_)); 

我以類似於COMMANDLINE有使用被定義爲

while (std::find(lexeme_.begin(),lexeme_.end(),std::string(&commandLine_.at(position_))) == lexeme_.end())    
{ 
    // Concat each successive alphanumeric character to 'token' 
    token += commandLine_.at(position_); 
    // Update the index into 'commandLine' 
    position_ += 1; 
} 

評價std::find應該一char在lexeme_比較進行評估,以一個char此Java表達式

!lexeme.contains(Character.toString(commandLine.charAt(position))) 

評估應該比較char s,如果它確定在中的char在比較中得到滿足,則while循環將退出。

測試用例

#include<algorithm> 
#include<iostream>  

static const std::string delimiters_[] = {" ", ",", "(", ")", ";", "=", ".", "*", "-"}; 

static std::vector<std::string> lexeme_(std::begin(delimiters_), std::end(delimiters_)); 

std::string commandLine = "check me"; 

while (std::find(lexeme_.begin(),lexeme_.end(),std::string(&commandLine_.at(position_))) == lexeme_.end())    
{ 
    std::cout "I should stop printing when encountering a space ' ' << std::endl; 
} 
+1

你可以構建一個完整的測試用例來證明這一點? – 2013-04-08 21:30:52

+0

@DrewDormann需要引用。如上所述,這是可笑的。這當然不是「確實」更快。 – sehe 2013-04-08 21:33:29

+0

那麼問題是什麼?這段代碼做了什麼,你期望它做什麼,它做的與你期望的做法有什麼不同?總之,http://whathaveyoutried.com/ – jalf 2013-04-08 21:34:35

回答

3

您的臨時比較字符串的構造函數不正確。它不會構建單字符字符串,它將構建一個字符串,並在該字符處開始,並返回到原始字符串的末尾(如果幸運的話) - 可能會有一些std::string實現在某處,但不會自動爲零終止內部緩衝區。

所以不是這樣的:

std::string(&commandLine_.at(position_)) 

用途:

std::string(1, commandLine_.at(position_)) 
+0

謝謝。此外,將'delimiters_'轉換爲'char'數組並將'lexeme_'轉換爲'std :: vector '也適用。 – Mushy 2013-04-08 21:57:37

2

該表達式:

std::string(&commandLine_.at(position_)) 

通過將指針傳遞到一個char對象創建一個std::string對象。但是,指向char對象的指針是(空終止的)C字符串,而不是指向單個字符的指針。

沒有std::string的構造函數接受單個字符。您可以使您的矢量成爲char s的矢量,然後在該矢量內搜索commandLine_.at(position_)

然而,從測試情況來看,在我看來,所有你想要的是std::stringfind_first_of()成員函數:

#include <algorithm> 
#include <iostream> 

int main() 
{ 
    std::string commandLine = "Check me"; 
    std::string delimiters = " ,();=.*-"; 
    auto pos = commandLine.find_first_of(delimiters); 
    std::cout << pos; 
} 

這裏是一個live example

+0

順便說一句,如果他沒有找到,他會進入while循環;而不是當他發現。 (無論他在找什麼) – 2013-04-08 21:42:12

+0

@stardust_:對,這是複製粘貼出錯的結果。反正我編輯過,謝謝 – 2013-04-08 21:49:20