sortowanie vectora

0

Witam, mam taki program, do vektora wczytuje liczby i chce je posegregować, jednak pokazuje mi błędy.

#include<iostream>
#include<fstream>
#include<algorithm>
#include<vector>

using namespace std;

bool sortuj(const vector<int>& el1, const vector<int>& el2) {
	return el1 < el2;
}

int main() {
	fstream file;
	file.open("plik.txt", ios::in);
	vector<int> vec;
	if (file.is_open()) {
		while (!file.eof()) {
			int tmp;
			file >> tmp;
			vec.push_back(tmp);
		}
		cout << "przed sortowaniem";
		for (auto it = vec.begin(); it!=vec.end(); it++) {
			cout << *it << " ";
		}

		sort(vec.begin(), vec.end(), sortuj);
		cout << "po sortowaniu";
		for (auto it = vec.begin(); it != vec.end(); it++) {
			cout << *it << " ";
		}

		file.close();
	}
	else {
		cout << "blad odczytu";
	}
}

błędy: Błąd C2664 „bool (std::vector<int,std::allocator<_Ty>> &,std::vector<_Ty,std::allocator<_Ty>> &)”: nie można dokonać konwersji argumentu 2 z „int” do „std::vector<int,std::allocator<_Ty>> &” 3907

w czym problem?

1
bool sortuj(const vector<int>& el1, const vector<int>& el2) {
    return el1 < el2;
}

Elementem wektora nie jest on sam. Masz podać funkcję/obiekt porównującą elementy. W ogóle, tutaj użyj po prostu std::less zamiast wydziwiać. Albo niczego nie podawaj, bo to domyślne sortowanie.

0

Dziękuje, już rozumiem. Sugerowałem się bardziej skomplikowanym przykładem z zajęć, gdzie było to potrzebne. Dzięki za wytłumaczenie :D

0

Mam jeszcze jeden problem, tym razem mam strukturę i listę struktury i chce posortować studentów wg ocen:

struct Studenci {
	string imie;
	string nazwisko;
	float ocena;
};

bool comp(Studenci &a, Studenci &b) {
	if (a.ocena > b.ocena)
		return true;
	else
		return false;

int main() {

	fstream file;
	file.open("students.txt", ios::in);
	list<Studenci> lista;
	if (file.is_open()) {
		while (!file.eof()) { //do konca pliku
			Studenci tmp;
			file >> tmp.imie;
			file >> tmp.nazwisko;
			file >> tmp.ocena;
			lista.push_back(tmp);
         }
         sort(lista.begin(), lista.end(), comp);
		 file.close();
	}

i tym razem pokazuje takie błędy:

1

Lista nie ma random access iteratorów, musisz użyć jej metody sort (albo lepiej: nie używać listy). Ponadto nie kończysz funkcji comp

0

Nie wiedziałem, że listę się inaczej sortuje, jeszcze raz dziękuję za pomoc. ;)

1 użytkowników online, w tym zalogowanych: 0, gości: 1