0

I have an array of [2,3,4,3,4,5,6,3] now I want to know how many 3's are there in an array. Is there any short cut to do it rather than going through the loop and checking each element?

3
  • What do you mean by shortcut? performant way? Commented May 1, 2012 at 15:09
  • Saeed's point is very valid. "short cut" by way of concise source code, or shortcut for performance? For performance, obviously you might get benefits from parallel searches in different parts of a very large array. But each thread still has to do element by element comparison. There are almost certainly faster assembly langauge commands than the naive compilation of a loop doing comparisons - your compiler might or might not use them - but there's nothing directly specifiable in C++. Commented May 1, 2012 at 16:18
  • I mean in terms of no. of lines of code! Commented May 1, 2012 at 16:26

1 Answer 1

7

Use std::count from <algorithm>:

std::count(array.begin(), array.end(), 3) // or if it's a raw array: std::count(array, array + NUM_OF_ELEMENTS, 3) // or the most generic solution (std::{begin,end} are from C++11): std::count(std::begin(array), std::end(array), 3) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.