Ternary Operator in this function

Hello, I was searching for a solution to a challenge and this was one of the answers, but I can't understand the for(int y:arr). What does it mean? Thank you for your attention

1
2
3
4
5
6
7
8
9
  
int getAbsSum(std::vector<int> arr) {
  int x=0;
  for (int y:arr)
  {
    x+= abs(y);
  }
  return x;
}
Last edited on
That isn't a ternary operator. It's the syntax of a "for-each loop".
It's saying "for each item in arr, <perform statements>".
https://www.learncpp.com/cpp-tutorial/for-each-loops/

Also known as a "range-based for loop" officially.
Last edited on
Thank you very much, I could understand much better now. (: Have a good day
It's not good code though - as arr is passed by value not by const ref - so an unnecessary copy of the vector is made.

1
2
3
4
5
6
7
8
int getAbsSum(const std::vector<int>& arr) {
	int x {};

	for (int y : arr)
		x += abs(y);

	return x;
}

Topic archived. No new replies allowed.