Thread: STL Question (frequency)

  1. #1
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361

    STL Question (frequency)

    Is there any algorithm included in the STL which allows you to find the frequency (or "mode") of an element in one of the standard containers? I couldn't find any info in the reference; perhaps I was searching for the wrong name.

    Thanks in advance.

  2. #2
    Open to suggestions Brighteyes's Avatar
    Join Date
    Mar 2003
    Posts
    204
    What about count or count_if?
    Code:
    #include <algorithm>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        int list[] = {1,2,3,3,1,2,3,5,4,3,2,4,2,3,1};
        vector<int> vlist(list, list + 15);
        
        vector<int>::difference_type n(count(vlist.begin(), vlist.end(), 3));
        cout<<"There are "<< n <<" 3's in vlist"<<endl;
        
        cin.get();
    }
    Last edited by Brighteyes; 04-23-2003 at 09:03 AM.
    p.s. What the alphabet would look like without q and r.

  3. #3
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    With frequency, do you mean number of occurrences? (I'm not sure what "mode" means in this context)

    If so, use the count algorithm:
    Code:
    vector<int> vec = ....
    ...
    //Obtain the frequency of 2
    cout << count(vec.begin(),vec.end(),2);
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  4. #4
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Originally posted by Sang-drax
    With frequency, do you mean number of occurrences? (I'm not sure what "mode" means in this context)

    If so, use the count algorithm:
    Code:
    vector<int> vec = ....
    ...
    //Obtain the frequency of 2
    cout << count(vec.begin(),vec.end(),2);
    Yes, number of occourences. Thanks to you both for the help.
    Last edited by Eibro; 04-23-2003 at 09:14 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  2. STL preformance question
    By l2u in forum C++ Programming
    Replies: 9
    Last Post: 12-07-2006, 05:36 PM
  3. Quick Question about the Efficiency of the STL
    By Reisswolf in forum C++ Programming
    Replies: 8
    Last Post: 08-17-2006, 10:03 AM
  4. Replies: 5
    Last Post: 11-20-2003, 01:27 AM
  5. question about STL
    By free2run in forum C++ Programming
    Replies: 2
    Last Post: 12-16-2002, 12:12 PM