removing the auto keyword

This commit is contained in:
Jidong Xiao
2024-02-09 16:12:14 -05:00
parent 560bf9fcb9
commit 989133ee1d
2 changed files with 32 additions and 19 deletions

View File

@@ -206,7 +206,6 @@ int main() {
The following [example](list_sort_objects2.cpp) also demonstrates how to call the list sort function to sort a list which contains class objects.
```cpp
#include <iostream>
#include <list>
@@ -221,13 +220,14 @@ public:
// Constructor
Person(std::string name, int age) : name(name), age(age) {}
// Overload the < operator for sorting
bool operator<(const Person& other) const {
// Compare based on age
return age < other.age;
}
};
// Overload the < operator for sorting
bool operator<(const Person& p1, const Person& p2) {
// Compare based on age
return p1.age < p2.age;
}
int main() {
// Create a list of Person objects
std::list<Person> people = {
@@ -238,8 +238,11 @@ int main() {
// Print the original list
std::cout << "Original list:" << std::endl;
for (const auto& person : people) {
std::cout << person.name << " (" << person.age << ")" << std::endl;
std::list<Person>::iterator itr = people.begin();
while(itr != people.end()){
// one way to use iterators
std::cout << (*itr).name << " (" << (*itr).age << ")" << std::endl;
++itr;
}
// Sort the list of Person objects
@@ -247,8 +250,11 @@ int main() {
// Print the sorted list
std::cout << "\nSorted list:" << std::endl;
for (const auto& person : people) {
std::cout << person.name << " (" << person.age << ")" << std::endl;
itr = people.begin();
while(itr != people.end()){
// another way to use iterators
std::cout << itr->name << " (" << itr->age << ")" << std::endl;
++itr;
}
return 0;

View File

@@ -11,13 +11,14 @@ public:
// Constructor
Person(std::string name, int age) : name(name), age(age) {}
// Overload the < operator for sorting
bool operator<(const Person& other) const {
// Compare based on age
return age < other.age;
}
};
// Overload the < operator for sorting
bool operator<(const Person& p1, const Person& p2) {
// Compare based on age
return p1.age < p2.age;
}
int main() {
// Create a list of Person objects
std::list<Person> people = {
@@ -28,8 +29,11 @@ int main() {
// Print the original list
std::cout << "Original list:" << std::endl;
for (const auto& person : people) {
std::cout << person.name << " (" << person.age << ")" << std::endl;
std::list<Person>::iterator itr = people.begin();
while(itr != people.end()){
// one way to use iterators
std::cout << (*itr).name << " (" << (*itr).age << ")" << std::endl;
++itr;
}
// Sort the list of Person objects
@@ -37,8 +41,11 @@ int main() {
// Print the sorted list
std::cout << "\nSorted list:" << std::endl;
for (const auto& person : people) {
std::cout << person.name << " (" << person.age << ")" << std::endl;
itr = people.begin();
while(itr != people.end()){
// another way to use iterators
std::cout << itr->name << " (" << itr->age << ")" << std::endl;
++itr;
}
return 0;