c++ - 对 vector C++ 中的上界

标签 c++ algorithm visual-c++ data-structures stl-algorithm

#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();
}

我对这对 vector 进行了排序,我试图获取这对 vector 中一个 vector 的 upper_bound 值,但它给了我 upper_bound 在位置 = 0。

请耐心等待,我是c++的新手,想学习。请帮助修复此代码。谢谢

最佳答案

据我所知,您从未将任何数据放入 SP vector 中。有可能不是 int SP = ptr->second; 你的意思是 SP.push_back(ptr->second);

作为旁注,由于排序不稳定,因此在使用谓词对其进行排序之前调用 sort( pair.begin(), pair.end() ); 没有意义。

最后,你不妨在The Definitive C++ Book Guide and List中挑选一本书帮助您学习语言。

关于c++ - 对 vector C++ 中的上界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226275/

相关文章:

c++ - 谷歌 Protocol Buffer - 位错误的概率以及减少错误的方法

javascript - 一个字符串可以有一个回文,有没有更好的方法来做到这一点?

algorithm - 计算大型数据集中位数的内存高效方式?

c++ - 在代码中捕获异常

c++ - 确定内存位置是否更改值

c++ - 由 JOB 中的进程启动的子进程能否将 JOB 属性设置为脱离作业?

c++ - 多态指针的typeid?

python - 标准化范围 (0.0, 1.0) 中的列表数据

c++ - 如何在 Visual C++ 中同时创建 .lib 文件和 .exe 文件?

c++ - C++ 函数签名中 `struct` 的使用定义良好吗?