tags:

views:

215

answers:

3

Hi, I have a list L which needs to count how many 1s it has in it.

list<int> L;

L.push_back(14); L.push_back(5); L.push_back(22);

L.push_back(1); L.push_back(1); L.push_back(-7);

the function that i have been given is :

assert ( count(...,...,...) == 2);

i need to know what would replace the ...'s.

i have tried L.begin(), L.end(), 1 to replace the ...'s but it keeps giving me an error saying that is not allowed. So i need to replace the ...'s without adding any extra code.

this is the error that i have been getting:

error C2782: 'iterator_traits<_Iter>::difference_type std::count(_InIt,_InIt,const _Ty &)' : template parameter '_InIt' is ambiguous

Here is the exact code & error.

#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <cassert>
using namespace std;


int main()
{
    int A1[6] = {15,8,10,9,12,13};
    vector<int> V(A1, A1+6);
    list<int> L; 

    L.push_back(14); L.push_back(5); L.push_back(22);
    L.push_back(1); L.push_back(1); L.push_back(-7);

    count(L.begin(), L.end(), 1);

}

error C2782: 'iterator_traits<_Iter>::difference_type std::count(_InIt,_InIt,const _Ty &)' : template parameter '_InIt' is ambiguous

c:\program files\microsoft visual studio 9.0\vc\include\algorithm(160) : see declaration of 'std::count' 1>
could be 'unsigned int'

+5  A: 

it should be std::count(L.begin(), L.end(), 1) so if this doesn't work all I can say is make sure you #include <algorithm>.

This code compiles for me in VS2008:

#include <list>
#include <algorithm>
#include <cassert>
using namespace std;

int main()
{
    list<int> L;

    L.push_back(14); L.push_back(5); L.push_back(22);

    L.push_back(1); L.push_back(1); L.push_back(-7);

    assert( count(L.begin(), L.end(), 1) == 2);
}
rlbond
I have included the #include<algorithm> but it still doesnt work. the error it shows is that the parameters are too ambigious.
Zeeshan Raja
Zeeshan Raja
A: 

Use std::count_if

http://www.sgi.com/tech/stl/count%5Fif.html

Heres a beter sample: http://msdn.microsoft.com/en-us/library/w2d7w2x2%28VS.80%29.aspx

RED SOFT ADAIR
i have to use count() because thats whats been given to me. can't add any extra code
Zeeshan Raja
You don't need `count_if` here.
rlbond
A: 

Make sure you put using namespace std; after all the includes and make sure you include algorithm also and then L.begin() and L.end() should work without any problem

VNarasimhaM