c++c++11multiset

Retrieve the value stored in a multiset


I am trying to retrieve the value that is stored in a particular spot in a mulitset, but all I'm unable to find out how to do that anywhere online. This is also my first time using multisets in C++.

The multiset that I want to get the value from is the numerator, and it's declared in the header file that I attached to my program. Below is what I have tried.

// This method will swap the numerator and denominator values
void Fraction::Invert() {
    int tmp = 0;

    for (int i = 0; i < (int)numerator.size(); i++) {
        // I want the value stored in the multiset (numerator) at i
        tmp = numerator.find(i);
    }
}

Solution

  • Many methods exist so you can retrieve a value from a multiset.

    First:

    You can use an iterator. Something like below:

        for (auto cit = numerator.cbegin(); cit != numerator.cend(); cit++)
            std::cout << *cit << std::endl;
    

    In the your example, it is like below:

    // This method will swap the numerator and denominator values
    void Fraction::Invert() {
        int tmp = 0;
    
        auto cit = numerator.cbegin();
        for (int i = 0; i < (int)numerator.size() && cit != numerator.cend(); i++, cit++) {
            // I want the value stored in the multiset (numerator) at i
            tmp = *cit; // *cit is the value of i'th number of multiset
        }
    }
    

    Second:

    You can use the range for style:

        for (auto value : numerator)
            std::cout << value << std::endl;
    

    And in the your example, it is like below:

    // This method will swap the numerator and denominator values
    void Fraction::Invert() {
        int tmp = 0;
    
        int i = 0;
        for (auto value : numerator) {
            // I want the value stored in the multiset (numerator) at i
            tmp = value; // value is the value of i'th number of multiset
            ++i;
        }
    }