Loading Now

[STL_C++]removeElements2

STL C++List

Bài tập:

Cho một list chứa các số nguyên và một số nguyên n, hãy xóa những phần tử có giá trị lớn hơn hoặc bằng n trong list đó.

Ví dụ:

  • Với v = [1, 4, 2]n = 3, thì verifyFunction(v) = [1, 2].

  • Với v = [4, 2, 2, 1, 1]n = 2, thì verifyFunction(v) = [1, 1].

Lý thuyết.

Để xóa phần tử trong list ta dùng hàm erase() (độ phức tạp bằng số phần tử cần xóa).

Muốn xóa phần tử ở interator it, ta làm như sau:

	a.erase(it);

 

Muốn xóa phần tử thứ k trong list a, ta làm như sau.

	list<int>:: iterator it = a.begin();
	advance(it,k-1);
	a.erase(it);

 

Muốn xóa một lúc nhiều số, ta làm như sau:

	a.erase(iteratorFirst,iteratorLast);

 

Ví dụ như muốn xóa phần tử thứ x đến phần tử thứ k (k≥x) trong list a, ta làm như sau:

	list<int>:: iterator it = a.begin();
	advance(it,x-1);

	list<int>:: iterator it2 = a.begin();
	advance(it2,k);

	a.erase(it1, it2);

 

Hướng dẫn.

Sau khi xóa một phần tử này sẽ không biết nó được nối tiếp với phần tử nào nên hãy cẩn thận việc chọn phần tử để xóa và phần tử để duyệt.

Code mẫu:

list<int> removeElements(list<int> linkedList, int n) {
    list<int>::iterator i = linkedList.begin(), j;
    for (; i != linkedList.end(); i++) {
        if (*i >= n) {
            j = i;
            i--;
            linkedList.erase(j);
        }
    }
    return linkedList;
}

vector<int> verifyFunction(vector<int> v, int n) {
	list<int> l(v.begin(), v.end());
    l = removeElements(l, n);
    vector<int> vec(l.begin(), l.end());
	return vec;
}

hoặc

list<int> removeElements(list<int> linkedList, int n) {
    for (list<int>::iterator it = linkedList.begin(); it != linkedList.end(); it++) {
		if (*it >= n) {
			it = linkedList.erase(it);
			it--;
		}
	}
	return linkedList;
}

vector<int> verifyFunction(vector<int> v, int n) {
	list<int> l(v.begin(), v.end());
    l = removeElements(l, n);
    vector<int> vec(l.begin(), l.end());
	return vec;
}

Post Comment

Contact