2013-04-08 3 views
0

std :: find가 예상대로 평가되지 않습니다.std :: find가 예상대로 작동하지 않습니다.

은 내가 유사한 명령 줄에서 char에 lexeme_에 char을 비교하도록되어

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를 사용하여 평가를

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

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

는 벡터 lexeme_가 정의한 이 Java 표현

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

평가 결과가 char과 비교되며, 에있는 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

당신이 완전한 테스트 케이스를 만들 수 있습니다 이것을 설명하기? –

+0

@DrewDormann은 인용이 필요합니다. 말했듯이 그것은 우스꽝 스럽다. 확실히 "확실히"빠르지는 않습니다. – sehe

+0

그래서 문제가 무엇입니까? 이 코드는 무엇을하고 무엇을 기대합니까? 그리고 그것이하는 일과 기대 한 것과는 어떻게 다릅니 까? 간단히 말해서, http://whathaveyoutried.com/ – jalf

답변

3

임시 비교 문자열의 생성자가 잘못되었습니다. 단일 문자 문자열을 만드는 것이 아니라, 운좋게도 그 문자에서 시작하여 원래 문자열의 끝으로 이동하는 문자열을 작성합니다. 자동으로 0이 아닌 어딘가에서 std::string 구현이있을 수 있습니다. 내부 버퍼를 종료한다.

그래서 대신의 :

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

사용 :

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

감사합니다. 또한,'delimiters_'를'char' 배열로 변환하고'lexeme_'를'std :: vector '으로 만드는 것도 효과적입니다. – Mushy

2

이 식 :

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

char 객체에 대한 포인터를 전달함으로써 std::string 객체를 생성한다. 그러나 char 개체에 대한 포인터는 단일 문자에 대한 포인터가 아닌 (null로 끝나는) C 문자열입니다.

단일 문자를 허용하는 std::string의 생성자가 없습니다. 당신은 당신의 벡터를 char s의 벡터로 만들 수 있고 그 벡터 안에서 commandLine_.at(position_)을 검색 할 수 있습니다. 여기

#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입니다 :

그러나, 테스트 케이스에서 판단, 당신이 원하는 모든 std::stringfind_first_of() 멤버 함수입니다 날 것으로 보인다.

+0

BTW 그가 찾지 못하면 그는 while 루프로 들어갑니다. 그가 찾은 때가 아니라. (그가 무엇을 찾고 있든간에) –

+0

@stardust_ : 맞습니다. 그게 잘못된 복사 결과입니다. 어쨌든 편집했습니다. 감사합니다. –

관련 문제