2011-08-29 1 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

도와 주셔서 감사합니다. –

+0

도'int (up-pair.begin())'대신'distance (pair.begin(), up)'을 사용합니다. –