BitMagic-C++
sample17.cpp
Go to the documentation of this file.
1 /*
2 Copyright(c) 2002-2017 Anatoliy Kuznetsov(anatoliy_kuznetsov at yahoo.com)
3 
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7 
8  http://www.apache.org/licenses/LICENSE-2.0
9 
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 
16 For more information please visit: http://bitmagic.io
17 */
18 
19 /** \example sample17.cpp
20 Example rank and select operations.
21 
22 */
23 
24 /*! \file sample17.cpp
25  \brief Example: rank and select operations using rank-select index
26 */
27 
28 #include <stdlib.h>
29 #include <iostream>
30 #include <vector>
31 #include <memory>
32 
33 #include "bm.h"
34 
35 int main(void)
36 {
37  try
38  {
39  bm::bvector<> bv { 1, 20, 30, 31 }; // init a test bit-vector
40 
41  // construct rank-select index
42  std::unique_ptr<bm::bvector<>::rs_index_type>
43  rs_idx(new bm::bvector<>::rs_index_type());
44  bv.build_rs_index(rs_idx.get());
45 
46  // lets find a few ranks here
47  //
48  auto r1 = bv.rank(20, *rs_idx);
49  std::cout << r1 << std::endl; // 2
50 
51  r1 = bv.rank(21, *rs_idx);
52  std::cout << r1 << std::endl; // still 2
53 
54  r1 = bv.rank(30, *rs_idx);
55  std::cout << r1 << std::endl; // 3
56 
57 
58  // now perform a search for a position for a rank
59  //
61  bool found = bv.select(2, pos, *rs_idx);
62  if (found)
63  std::cout << pos << std::endl; // 20
64  else
65  std::cout << "Rank not found." << std::endl;
66 
67  found = bv.select(2, pos, *rs_idx);
68  if (found)
69  std::cout << pos << std::endl; // 30
70  else
71  std::cout << "Rank not found." << std::endl;
72 
73  found = bv.select(5, pos, *rs_idx);
74  if (found)
75  std::cout << pos << std::endl;
76  else
77  std::cout << "Rank not found." << std::endl; // this!
78 
79  }
80  catch(std::exception& ex)
81  {
82  std::cerr << ex.what() << std::endl;
83  return 1;
84  }
85 
86 
87  return 0;
88 }
89 
90 
Compressed bit-vector bvector<> container, set algebraic methods, traversal iterators.
rs_index< allocator_type > rs_index_type
Definition: bm.h:1255
bm::id_t size_type
Definition: bm.h:117
bool select(size_type rank, size_type &pos, const rs_index_type &rs_idx) const
select bit-vector position for the specified rank(bitcount)
Definition: bm.h:4158
int main(void)
Definition: sample17.cpp:35