2011-08-29 94 views
2
#include <algorithm> 
#include <iostream> 
#include <iterator> 
#include <string> 
#include <vector> 
#include <utility> 

using namespace std; 

typedef pair<int,int> Pair; 

inline bool less_than_second(const Pair& b1, const Pair& b2){ 
    return b1.second < b2.second; 
} 

int main() 
{ 
    const int SP1[] = { 2,53,21,55,36,5,1}; 
    const int EP1[] = { 18, 20, 26, 30, 41,1,5 }; 
     int i; 


    const int num_pairs = sizeof(SP1)/sizeof(SP1[0]); 
    vector<int> sm(num_pairs); 

     // vector <int> SP; 

    vector<Pair> pair(num_pairs); 
    transform(EP1, EP1+num_pairs, SP1,pair.begin(), make_pair<int,int>);// MAKE PAIR 

    sort(pair.begin(), pair.end()); 

    sort(pair.begin(), pair.end(), less_than_second); 

    vector<Pair>::const_iterator pair_end = pair.end(); 
    vector<int> SP,EP; 
    vector<int>::iterator low,up; 

    for(vector<Pair>::const_iterator ptr = pair.begin();ptr != pair_end; ++ptr) 
    { 

      int SP = ptr->second; 
     int EP = ptr->first; 

     cout<<"("<<SP<<","<<EP<<")\n"; 
     } 
    //cout<<"("<<SP<<","<<EP<<")\n"; 
    low=lower_bound (SP.begin(), SP.end(), 20); 
    up= upper_bound (SP.begin(), SP.end(), 20); 

    cout << "lower_bound at position " << int(low- SP.begin()) << endl; 
    cout << "upper_bound at position " << int(up - SP.begin()) << endl; 


    up= upper_bound (pair.begin(), pair.end(), 20);     


    cout << "upper_bound at position " << int(up - pair.begin()) << endl; 

    getchar(); 
} 

結合我排序的一對向量和我試圖獲得一個對中的向量的UPPER_BOUND的值,但它給我在位置 UPPER_BOUND = 0上在一對矢量C++

請耐心等待,我是C++的新手,想學習。請幫助解決這個問題。謝謝

回答

2

據我所知,你從來沒有把任何數據到SP載體。這可能不是int SP = ptr->second;你的意思是SP.push_back(ptr->second);

作爲一個側面說明,因爲排序是不是穩定有呼籲sort(pair.begin(), pair.end());你與你的謂詞進行排序之前,沒有任何意義。

最後,你不妨拿起一本書在The Definitive C++ Book Guide and List幫助你學習語言。

+0

非常感謝你的''而不是INT,幫助 –

+0

也可以使用'距離(pair.begin(),向上)(最多 - pair.begin())' –