2015-11-06 83 views
-1

我遇到了以下问题:假设我有使用find与矢量<对<int, int>>

pair<int, int> p(1,2) 
vector<pair<int, int>> vec; 

我想用找到一条获取指向元素p向量中的迭代器

find(vec.begin(), vec.end(), p) 

但它给我的错误

type 'std::__1::pair<int, int>' does not provide a call operator 

我应该怎么做?

+0

你缺少一个分号。 –

+1

[Works](http://coliru.stacked-crooked.com/a/3310f63bca8b7a63)。请发布[SSCCE](http://sscce.org) – Praetorian

+0

您能否提供完整的示例? –

回答

-1

这是我用过的,它的效果很好。

#include <iostream> 
#include <vector> 
#include <algorithm> 

struct FindPair { 
    FindPair (int first, int second) 
    : m_first_value(first) 
    , m_second_value(second) { } 

    int m_first_value; 
    int m_second_value; 
    bool operator() 
     (const std::pair<int, int> &p) { 
      return (p.first == m_first_value && p.second == m_second_value); 
    } 
}; 


int main() 
{ 

    std::vector< std::pair<int, int> > myVec; 
    std::vector< std::pair<int, int> >::iterator it; 

    myVec.push_back(std::make_pair(1,1)); 
    myVec.push_back(std::make_pair(1,2)); 

    it = std::find_if(myVec.begin(), myVec.end(), FindPair(1, 2)); 

    if (it != myVec.end()) 
    { 
     // We Found it 
     std::cout << "Matched Found on Current Iterator!" << std::endl; 
     std::cout << "it.first: " << (*it).first << std::endl; 
     std::cout << "it.second: " << (*it).second << std::endl; 
    } 
    else 
    { 
     std::cout << "Nothing Matched!" << std::endl; 
    } 

    return 0; 
} 

输出:

Matched Found on Current Iterator! 
it.first: 1 
it.second: 2 
+2

OP使用“pair”中的第一个元素不会说任何他想要比较的地方。既然他想比较两个元素,'find'可以工作,因为'operator =='是为'pair'定义的。 – Praetorian

+0

您的正确,我已经更新了我的答案,以便更完整。 – Mercyful

+0

为什么你仍然在使用'find_if'和'FindPair'?这里有一个简单版本的示例 - http://coliru.stacked-crooked.com/a/2be33cdeef2db054 – Praetorian

相关问题