w3resource

C++ Exercises: Prints the word and a list of the corresponding page numbers


Word with Page Numbers

Write a C++ program that reads a list of pairs of a word and a page number, and prints the word and a list of the corresponding page numbers.

Sample Solution:

C++ Code :

#include <iostream>
#include <vector>
#include <algorithm> // Required for sort()
using namespace std;

// Define a pair alias for string and int
typedef pair<string, int> P;

int main()
{
    string str;
    int page, ctr = 0;
    vector<P> v_data; // Vector of pairs to store string and int pairs

    // Input loop: Read string and integer pairs until the end of input
    while (cin >> str >> page) {
        v_data.push_back(P(str, page)); // Store the pair (string, int) in the vector
        ctr++;
    }

    // Sort the vector of pairs based on string (lexicographical order)
    sort(v_data.begin(), v_data.end());

    // Loop through the sorted vector of pairs
    for (int i = 0; i < ctr; i++) {
        if (i == 0) {
            cout << v_data[i].first << endl; // Print the first string
            cout << v_data[i].second; // Print the first associated integer
            continue;
        }

        // Check if the current string is the same as the previous string
        if (v_data[i].first == v_data[i - 1].first && v_data[i].second != v_data[i - 1].second) {
            cout << ' ' << v_data[i].second; // If the strings match but integers don't, print the current integer
            continue;
        } else {
            cout << endl; // Print a newline when the strings differ
        }

        cout << v_data[i].first << endl; // Print the current string
        cout << v_data[i].second; // Print the associated integer
    }

    puts(""); // Print a newline at the end
    return 0;
}

Sample Output:

Sample Input: Python 2
HTML  4
CSS    3
Python 5
Python 3
HTML  2
CSS   6
Output:
CSS
3 6
HTML
2 4
Python
2 3 5

Flowchart:

Flowchart: Prints the word and a list of the corresponding page numbers

For more Practice: Solve these Related Problems:

  • Write a C++ program to read pairs of words and page numbers, then print each word followed by a sorted list of its associated page numbers.
  • Write a C++ program that stores word-page pairs in a map and then prints each word with its corresponding page numbers in ascending order.
  • Write a C++ program to create an index from a list of word and page number pairs, ensuring duplicate page numbers are merged.
  • Write a C++ program that accepts word-page pairs, then prints a formatted index with each word and a comma-separated list of page numbers.

Go to:


PREV : Replace "dog" with "cat".
NEXT : Convert Number to Hours and Minutes.

C++ Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.