开发者

C++ using list with count() function

开发者 https://www.devze.com 2022-12-08 00:38 出处:网络
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);

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'


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);
}


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


Use std::count_if

http://www.sgi.com/tech/stl/count_if.html

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

0

精彩评论

暂无评论...
验证码 换一张
取 消