Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain this code that uses std::ignore

Tags:

c++

c++11

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";     } } 

If someone can explain the code to me, it would be appreciated. Thanks.

like image 956
template boy Avatar asked Apr 26 '13 01:04

template boy


People also ask

What is STD ignore?

std::ignoreAn object of unspecified type such that any value can be assigned to it with no effect. Intended for use with std::tie when unpacking a std::tuple, as a placeholder for the arguments that are not used.

How do you ignore an entire line in C++?

1 Answer. Show activity on this post. cin. ignore(std::numeric_limits<std::streamsize>::max(), '\n');


1 Answers

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.

like image 108
David Avatar answered Sep 20 '22 23:09

David