C ++计算给出的不同数字

时间:2012-03-27 18:00:46

标签: c++ arrays vector

程序必须计算标准输入的不同数字。例如,输入时

6 <- how many numbers
1
3
1
4
3
786345

它应该发出

4

这是我的溶剂,虽然它太慢了。 是否有更快的方式?

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

vector<int> occured; //vector of numbers that occured already

/*
    int findType(int find)
    finds where given number should be, I want to keep this array sorted.
    in case of number existed already return -1; otherwise return the index for inserting.
*/
int findType(int find) 
{
    for (int i=0; i<occured.size(); i++) //for each number in occured array
        if (find==occured[i]) return -1; //if it is same return it occured
        else if (find<occured[i]) return i;
    return occuerd.size();
};

int main(int argc, char *argv[])
{
     int n; // read how many numbers will be given
    cin>>n;
    int tmp; //temp variables.
    int tmp2; 

    for (int i=0; i<n; i++) //for each number
    {
        cin>>tmp;       //get it
        if ((tmp2=findType(tmp))!=-1)  //check if it occured
           occured.insert(occured.begin()+tmp2,tmp); // if not add it to occured vector.
    }
    cout<<occured.size(); //print how many different numbers

    //system("PAUSE"); //uncomment if needed
    return 0;
}

2 个答案:

答案 0 :(得分:6)

如何使用std::set代替std::vector?它将确保不存在两次输入(您不必检查它;它也将被排序),而且您只需要获得大小以了解不同元素的数量。

示例:

std::set<int> occured;
int tmp;
int n = 10; // or input it

for (int i=0; i<n; i++) {
    cin >> tmp;
    occured.insert(tmp);
}

cout << occured.size();

答案 1 :(得分:3)

对于初学者,使用push_back()将输入插入到 std::vector。完成所有输入后,请使用std::sort和 向量上的std::unique。类似的东西:

std::vector<int> numbers;
int nextValue;
while ( std::cin >> nextValue ) {
    numbers.push_back( nextValue );
}
std::sort(numbers.begin(), numbers.end());
int results = std::unique(numbers.begin(), numbers.end()) - numbers.begin();