2016-04-20 27 views
-2

我有以下程序,程序的目的是显示列表向量中每个值发生多少次。没有找到预期的发生

如果元组2:3在矢量中出现3次,那么程序会将此显示给用户。

预期输出

  • 0:8发生1个%×
  • 2:3发生3次%×
  • 9:5发生2次%×
  • 8:9发生1次%x

实际输出:

  • 2:3发生3时间%42
  • 8:9发生1时间%14
  • 9:5发生3时间%42

任何想法我在做什么错误地?这是我正在使用的代码的完整且可验证的工作版本

任何帮助,非常感谢。

#include <vector> 
    #include <iostream> 
    #include <tuple> 

    using namespace std; 
    int counter = 0; 
    double percentage; 
    int val = 0; 
    vector<tuple<int, int>> list = { make_tuple(2, 3), make_tuple(0, 8), make_tuple(2, 3), make_tuple(8, 9), make_tuple(9, 5), make_tuple(9, 5), make_tuple(2, 3) }; 


     int binarysearch(vector<tuple<int, int>> list, int low, int high, tuple<int, int> number) 
     { 
      int index = low; 
      int mid = 0; 
      // loop till the condition is true 
      while (low <= high) { 
       // divide the array for search 
       mid = (low + high)/2; 

       if (list.at(mid) > number) { 
        high = mid - 1; 

       } 
       else { 
        low = mid + 1; 
       } 

      }return (high - index + 1); 

     } 

     int main() 
     { 

      while (counter <= list.size() - 1) { 

       val = binarysearch(list, counter, list.size() - 1, list.at(counter)); 
       percentage = val * 100/list.size(); 
       cout << "Value: " << get<0>(list.at(counter)) << ":" << get<1>(list.at(counter)) << " Occurs: " << val << " Time(s)" << " %" << percentage << endl; 
       counter += val; 
      } 



      return 0; 
     } 
+1

通过步进时的任何意见你的代码与调试器? –

+0

我没看见,现在看了几次。 – Mitch89

+0

我正在投票关闭这个问题作为一般调试的帮助,而不是自己做,而是询问SO然后删除Q来询问下一个Q,直到完成(赋值?)。 –

回答

1

您无法在未排序的容器上运行二进制搜索。二分搜索依赖于这样一个事实,如果中点不是你想要的元素,那么你想要的元素将在上半部分,如果它比中点更多,下半部分更少。你不能保证与一个未分类的容器。

现在不是写你自己的函数来获取每个出现的号码,您可以使用一个std::map做你喜欢

std::vector<std::tuple<int, int>> list = { make_tuple(2, 3), make_tuple(0, 8), make_tuple(2, 3), make_tuple(8, 9), make_tuple(9, 5), make_tuple(9, 5), make_tuple(2, 3) }; 
std::map<std::tuple<int, int>, int> occurrences; 
for (const auto& e : list) // go though the vector and add to the map. increment the value on duplication 
    ++occurrences[e]; 

for (const auto& e : occurrences) 
{ 
    double percentage = e.second * 100/list.size(); 
    cout << "Value: " << get<0>(e.first) << ":" << get<1>(e.first) << " Occurs: " << e.second << " Time(s)" << " %" << percentage << endl; 
} 

,输出:

Value: 0:8 Occurs: 1 Time(s) %14 
Value: 2:3 Occurs: 3 Time(s) %42 
Value: 8:9 Occurs: 1 Time(s) %14 
Value: 9:5 Occurs: 2 Time(s) %28 
+0

我用一个气泡排序来排序数组,然后我用我的二进制搜索,它的工作。尽管下次我会把地图带入想法。 – Mitch89