Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have an array of students with their First and Last Name
C++
std::string students[5] = {
"Michael, Fred", "Shane, Lewis", "James, Fred", "Dan, Hot", "Sam, Lewis", "James, Lewis"};

I have converted the following to the linked list in the code shown below.

I want to cout last name of the students but if its same last name to be printed once
so the console should look like
last name 1 = fred, 
last name 2 = lewis, 
last name 3 = hot,


I am not sure on how to compare the last names so any help would be great
Thank you

What I have tried:

C++
class node {
	string FirstName;
	string LastName;
	node* nextStudent = nullptr;
	node* nextSameLastName = nullptr;
};
node* find_student(node* start, std::string stu)
{
	if (start == nullptr)
	{
		return nullptr;
	}
	if (student->LastName == stu)
	{
		return start;
	}return find_student(start->nextStudent, stu);
}

void list_Student(node* n, node** r)
{
	if (*r == nullptr)
	{
		*r = n;
		return;
	}
	node* N = find_student(*r, n->LastName);
	if (N == nulptr)
	{
		node* t = *r;
		*r = n;
		n->nextStudent = t;
	}
	else
	{
		node* t = N->nextSameLastName;
		N->nextSameLastName = n;
		n->nextSameLastName = t;
	}
}
node* r = nullptr;

bool list(node** r, std::string students[], int num)
{
	for (int i = 0; i < num; i++)
	{
		std::string stu = students[i];
		std::string str = "";
		node* n = new node();
		for (char ch : str)
		{
			if (ch != ',')
			{
				str = str + c;
			}
			else
			{
				if (n->FirstName == "")
				{
					n->FirstName = str;
					str = "";
				}
				else
				{
					n->LastName = str;
					str = "";
				}
			}
		}
		list_student(n, r);
	
}
void samelastname(node* r)
{
	
}
Posted
Updated 13-Apr-21 20:01pm
v2

1 solution

The most straightforward way is using the power of the standard library:
C++
#include <iostream>
#include <list>
#include <set>

using namespace std;

struct Student
{
  string firstname;
  string lastname;
};

int main()
{
  list < Student > student_list { { "Michael", "Fred"}, {"Shane" , "Lewis" }, {"James" , "Fred"}, {"Dan", "Hot"}, {"Sam", "Lewis"}, {"James", "Lewis"}};

  set<string> lastname_set;

  for (const auto & student : student_list)
    lastname_set.insert( student.lastname );

  int counter = 0;
  for (const auto & lastname : lastname_set )
    cout << "lastname " << ++counter << " = " << lastname << endl;

}
 
Share this answer
 
Comments
Richard MacCutchan 14-Apr-21 3:41am    
Or rather, the power of CPallini. :))
CPallini 14-Apr-21 4:04am    
Thank you!
:-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900