计算向量中的出现 [英] Counting occurrences in a vector

查看:86
本文介绍了计算向量中的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序从txt文件中读取数字字符串,将其转换为整数,将其存储在矢量中,然后尝试以类似这样的有组织方式输出它们。...

This program reads strings of numbers from a txt file, converts them to integers, stores them in a vector, and then tries to output them in an organized fashion like so....

如果txt文件说:

7 5 5 7 3 117 5

程序输出:

3
5   3
7   2
117

所以如果数字发生不止一次,它输出发生了多少次。到目前为止,这里是代码。

so if the number occurs more than once it outputs how many times that happens. Here is the code so far.

#include "std_lib_facilities.h"

int str_to_int(string& s)
{
    stringstream ss(s);
    int num;
    ss >> num;
    return num;
}

int main()
{
    cout << "Enter file name.\n";
    string file;
    cin >> file;
    ifstream f(file.c_str(), ios::in);

    string num;
    vector<int> numbers;
    while(f>>num)
    {
        int number = str_to_int(num);
        numbers.push_back(number);
    }

    sort(numbers.begin(), numbers.end());

    for(int i = 0; i < numbers.size(); ++i)
    {
     if(i = 0 && numbers[i]!= numbers[i+1]) cout << numbers[i] << endl;
     if(i!=0 && numbers[i]!= numbers[i-1])
     {
          cout << numbers[i] << '\t' << counter << endl;
          counter = 0;
     }
     else ++counter;
    }
 }

编辑:程序被卡住了。

Program is getting stuck. Looking for an infinite loop right now.

推荐答案

如何使用地图,其中的关键是您要跟踪的数字,

How about using a map, where the key is the number you're tracking and the value is the number of occurrences?

如果必须使用向量,则已经对其进行了排序。因此,只需跟踪您之前看到的电话号码即可。如果与当前编号相同,则增加计数器。每次数字更改:打印当前数字和计数,重置计数,将last_seen数字设置为新数字。

If you must use a vector, you've already got it sorted. So just keep track of the number you previously saw. If it is the same as the current number, increment the counter. Every time the number changes: print out the current number and the count, reset the count, set the last_seen number to the new number.

这篇关于计算向量中的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆