Search code examples
c++stdtuplestd-tie

What is the purpose of std::ignore?


I'm reading the documentation on std::ignore from cppreference. I find it quite hard to grasp the true purpose of this object, and the example code doesn't do it much justice. For example, in the below code, how and why is inserted set to true? It doesn't make much sense to me.

#include <iostream>
#include <string>
#include <set>
#include <tuple>
 
int main()
{
    std::set<std::string> set_of_str;
    bool inserted;
    std::tie(std::ignore, inserted) = set_of_str.insert("Test");
    if (inserted) {
        std::cout << "Value was inserted sucessfully\n";
    }
}

Solution

  • set::insert returns a pair where first is the iterator to the inserted element and second is a bool saying whether the element was inserted.

    std::tie creates a tuple of lvalue references. When assigned to the result from insert it enables you to set the variables in the tie to the results of the insert in the return pair's first and second members.

    std::ignore is a value that can be assigned to with no effect.

    So basically, this code ignores the iterator to the element where "Test" was inserted and asigns inserted to the second member of the pair returned by set::insert that indicates whether the an element was inserted.