C++ 计算向量子集中的出现次数

C++ 计算向量子集中的出现次数,c++,C++,我将字符串标记为包含独立元素的向量。接下来,我想计算这个向量子集中字符串的出现次数。当我想简单地使用整个向量时,这就起作用了,正如下面提到的: 问题是我想使用向量的子集,我尝试了几种方法,但都不起作用: // Note: Here I count "NaN", which does not change the story. std::count (tokens.begin(start[i]), tokens.end(end[i]), "NaN") std::count (tok

我将字符串标记为包含独立元素的向量。接下来,我想计算这个向量子集中字符串的出现次数。当我想简单地使用整个向量时,这就起作用了,正如下面提到的:

问题是我想使用向量的子集,我尝试了几种方法,但都不起作用:

// Note: Here I count "NaN", which does not change the story.
std::count (tokens.begin(start[i]), tokens.end(end[i]), "NaN")        
std::count (tokens.begin() + start[i], tokens.end() + end[i], "NaN")
std::count (tokens + start[i], tokens + end[i], "NaN")
如何计算向量子集中的出现次数

以下是一个工作示例的上下文:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string line = "1 1 1 1 1 NaN NaN NaN";
    std::vector<int> start = {1,2,3,4};
    std::vector<int> end = {1,2,3,4};    
    istringstream iss(line);
    vector<string> tokens;
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter<vector<string> >(tokens));
    for (int i = 0; i < 3; i++)
     {
       cout<<std::count(tokens.begin() + start[i], tokens.end() + end[i], "NaN");
     }
}

Error: Segmentation fault
#包括
#包括
#包括
#包括
#包括
int main(){
使用名称空间std;
字符串行=“1楠楠楠”;
std::vector start={1,2,3,4};
std::vector end={1,2,3,4};
istringstream iss(线);
向量标记;
复制(istream_迭代器(iss),
istream_迭代器(),
背面插入器(令牌);
对于(int i=0;i<3;i++)
{

cout将整数添加到向量迭代器就像将整数添加到指针一样。因此,您可以执行以下操作,例如:

cout << std::count (tokens.begin() + 5, tokens.begin() + 10, 20);

您不能将正数添加到
令牌.end()
。您真正想要搜索的范围是什么?啊,是的,当然。它应该是
令牌.begin()+end[i]
(在
start==end
的示例中,您在空范围内计数,并且总是得到零。)在我的例子中,你可以看到我就是这样做的。你知道我为什么会出现错误吗?你正在添加到结束迭代器。你永远不应该这样做。相反,像我一样,将子数组的大小添加到添加到开始迭代器的值中。这是一个简单的错误,但却让我耽搁了一个小时。谢谢!
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string line = "1 1 1 1 1 NaN NaN NaN";
    std::vector<int> start = {1,2,3,4};
    std::vector<int> end = {1,2,3,4};    
    istringstream iss(line);
    vector<string> tokens;
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter<vector<string> >(tokens));
    for (int i = 0; i < 3; i++)
     {
       cout<<std::count(tokens.begin() + start[i], tokens.end() + end[i], "NaN");
     }
}

Error: Segmentation fault
cout << std::count (tokens.begin() + 5, tokens.begin() + 10, 20);