C++ Online Compiler
Example: Sort Names using std::sort in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sort Names using std::sort #include <iostream> // For input/output operations #include <vector> // For using std::vector to store names #include <string> // For using std::string objects #include <algorithm> // For the std::sort function int main() { // Step 1: Declare a vector of strings to store names std::vector<std::string> names; std::string name; int numNames; // Step 2: Get the number of names from the user std::cout << "Enter the number of names you want to sort: "; std::cin >> numNames; std::cin.ignore(); // Consume the newline character left by std::cin >> numNames // Step 3: Read names from the user std::cout << "Enter " << numNames << " names:\n"; for (int i = 0; i < numNames; ++i) { std::cout << "Name " << i + 1 << ": "; std::getline(std::cin, name); // Read full line including spaces names.push_back(name); } // Step 4: Sort the names using std::sort // std::sort works directly on std::string objects, comparing them alphabetically std::sort(names.begin(), names.end()); // Step 5: Print the sorted names std::cout << "\nNames in alphabetical order:\n"; for (const std::string& sortedName : names) { std::cout << sortedName << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS