【问题标题】:c++ search a vector for element first seen positionc++ 在向量中搜索元素第一次看到的位置
【发布时间】:2014-03-25 12:31:33
【问题描述】:

已解决
谢谢你。这解决了。这是我使用的解决方案。

std::vector<int> v = {1,2,3,4,8,8,8,8,9,10}
auto p = std::lower_bound(v.begin(),b.end(),8);
int position = p - v.begin();



我想找到一个元素在排序向量中的第一个看到的位置,我想使用 stl 来做到这一点。
示例:v = {1,1,2,6,7,8,8,8,8,9}

int position = my_fun(v.begin(),v.end(),8); // find the position of the first 8

那么位置是5。

看到这是一个排序的向量,我不想使用 find(),因为它每次都会从起点搜索。我想使用 binary_search() --- http://www.cplusplus.com/reference/algorithm/binary_search/,但 binary_search 只会返回 bool。
有什么建议吗?

【问题讨论】:

  • @sflee 您选择的答案无效。 :) 您不能取消引用等于 v.end() 的迭代器。看我的帖子。
  • @VladfromMoscow 我明白你的意思并更新了我的答案。

标签: c++ search


【解决方案1】:

你可以使用lower_bound()

vector<int>::const_iterator pos = std::lower_bound(v.begin(), v.end(), 8);
if (pos != v.end() && *pos == 8)
    return std::distance(v.begin(), pos);
return -1; // not found

【讨论】:

    【解决方案2】:

    您应该使用lower_bound function

    【讨论】:

      【解决方案3】:
      int item = 8;
      const auto posItr = std::lower_bound(std::begin(v), std::end(v), item);
      return (posItr != std::end(stuff) && *posItr == item) ? std::distance(std::begin(stuff), posItr) : -1;
      

      为什么我使用 std::begin 和 std::end 而不是容器一:

      【讨论】:

        【解决方案4】:

        你可以使用std::equal_range

        例如

        auto p = std::equal_range( v.begin(), v.end(), 8 );
        
        if ( p.first != p.second ) 
        {
           std::cout << "Position of the first element with value 8 is " 
                     << std::distance( v.begin(), p.first )
                     << std::endl;
        }
        

        或者你可以使用std::lower_bound:

        auto it = std::lower_bound( v.begin(), v.end(), 8 );
        
        if ( it != v.end() && *it == 8 ) 
        {
           std::cout << "Position of the first element with value 8 is " 
                     << std::distance( v.begin(), it )
                     << std::endl;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-08-28
          • 2013-01-20
          • 1970-01-01
          • 1970-01-01
          • 2011-01-21
          • 2021-02-14
          • 2019-10-04
          相关资源
          最近更新 更多