Loading Now

Access Elements In List Using Iterators

STL C++List

Bài tập.

Cho trước một list line.

Hãy tính tổng các phần tử trong list.

Ví dụ:

  • Với line = [4, 6, 2, 4], thì verifyFunction(line) = 16.
    Giải thích: Vì 4 + 6 + 2 + 4 = 16.

  • Với line = [3, 4, 5], thì verifyFunction(line) = 12.

Hướng dẫn.

Code mẫu:

int sumOfAllElements(list<int> linkedList)
{
	int sum = 0;
	for (list<int>:: iterator i=linkedList.begin(); i != linkedList.end(); i++){
		sum += *i;
	}
	return sum;
}

int verifyFunction(vector<int> v)
{
	list<int> l(v.begin(), v.end());
	return sumOfAllElements(l);
}

hoặc

int sumOfAllElements(list<int> linkedList)
{
   	int res = 0;
	for (auto i : linkedList) {
		res += i;
	}
	return res;
}

int verifyFunction(vector<int> v)
{
	list<int> l(v.begin(), v.end());
	return sumOfAllElements(l);
}

Post Comment

Contact