I tokenize a string into a vector containing seperate elements. Next, I want to count occurrences of a string in a subset of this vector. This worked when I want to simply use the whole vector with, as mentioned by the guide:
cout << std::count (tokens.begin(), tokens.end(), 20);
This will count all the occurrences of 20
.
Using an array it is possible to use a subset (from the guide):
int myints[] = {10,20,30,30,20,10,10,20}; // 8 elements
int mycount = std::count (myints, myints+8, 20);
The problem is that I want to use a subset of the vector, and I tried several things but they all do not work:
// 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")
How to count occurrences in a subset of a vector?
Here is the context for a working example:
#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