2013-04-08 73 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