2016-04-26 64 views
1

我期待下面的代码应该只打印出“2找到”,但它打印出两者。第二个不应该发生,因为4不在矢量的前3个元素中。我在哪里犯了错误?如何正确地从矢量的一部分中找到值?

#include <iostream> 
#include <vector> 
#include <algorithm> 
using namespace std; 

int main() 
{ 
    vector<int> a = {1,2,3,4,5}; 
    if(find(a.begin(),a.begin()+3,2) != a.end()) cout << "2 found" << endl; 
    if(find(a.begin(),a.begin()+3,4) != a.end()) cout << "4 found" << endl; 
} 

结果:

2 found 
4 found 
+4

'如果值没有找到,在这种情况下是*不*'a.end find'返回你通过它的终值()'。代码应该说'...!= a.begin()+ 3 ...'。 –

+0

@ n.m。我认为区间的右侧是开放的,所以它停在第三个元素上。 – daydayup

+2

@TonyD好的电话。它不能返回'a.end()',因为它不知道它是什么。 – NathanOliver

回答

3

find返回end/“最后” 你通过它,如果值没有找到,在这种情况下是不a.end()值。代码应该比较一个la ... != a.begin() + 3...

+0

谢谢先生,它的工作原理! – daydayup

+0

@daydayup:当然,不用担心。 –

1

变化find(a.begin(),a.begin()+3,2) != a.end()find(a.begin(),a.begin()+3,2) != a.begin()+3

#include <iostream> 
#include <vector> 
#include <algorithm> 
using namespace std; 

int main() 
{ 
    vector<int> a = {1,2,3,4,5}; 
    if(find(a.begin(),a.begin()+3,2) != a.begin()+3) cout << "2 found" << endl; 
    if(find(a.begin(),a.begin()+3,4) != a.begin()+3) cout << "4 found" << endl; 

}