gpt4 book ai didi

C++ 使用带有 count() 函数的列表

转载 作者:行者123 更新时间:2023-11-30 02:12:41 27 4
gpt4 key购买 nike

我有一个列表 L,它需要计算其中有多少个 1。

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(...,...,...) == 2);

我需要知道什么会取代 ...

我已经尝试用 L.begin(), L.end(), 1 来替换 ... 但它一直给我一个错误提示不允许。所以我需要在不添加任何额外代码的情况下替换 ...

这是我遇到的错误:

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

这是确切的代码和错误。

#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'

最佳答案

应该是std::count(L.begin(), L.end(), 1)所以如果这不起作用,我只能说确保你 #include <algorithm> .

此代码在 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);
}

关于C++ 使用带有 count() 函数的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1526546/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com