C++ - 从集合中打印出对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2793232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:42:03  来源:igfitidea点击:

C++ - Print Out Objects From Set

c++

提问by John Smith

If I have a C++ set and iterator:

如果我有一个 C++ 集和迭代器:

set<Person> personList;
set<Person>::const_iterator location;

How can I print out the contents of the set? They are all person objects, and I have overloaded operator<< for Person.

如何打印出集合的内容?它们都是 person 对象,我为 Person 重载了 operator<<。

The line that errors is in a basic for loop:

错误在基本 for 循环中的行:

cout << location

Netbeans gives:

Netbeans 提供:

proj.cpp:78: error: no match for ‘operator<<' in ‘std::cout << location'

proj.cpp:78: 错误:“std::cout << location”中的“operator<<”不匹配

It looks like it wants an overload for the iterator's operator<<.

看起来它想要迭代器的 operator<< 的重载。

Basically, I am taking objects that used to be stored in an array format, but are now in a set. What is the equivalent to cout << array[i]for sets?

基本上,我正在使用过去以数组格式存储的对象,但现在在一个集合中。什么是等价cout << array[i]于集合?

回答by Billy ONeal

In C++11, why use a for loop when you can use a foreach loop?

在 C++11 中,既然可以使用 foreach 循环,为什么还要使用 for 循环?

#include <iostream> //for std::cout

void foo()
{
    for (Person const& person : personList)
    {
        std::cout << person << ' ';
    }
}

In C++98/03, why use a forloop when you can use an algorithm instead?

在 C++98/03 中,for当您可以使用算法代替时,为什么要使用循环?

#include <iterator> //for std::ostream_iterator
#include <algorithm> //for std::copy
#include <iostream> //for std::cout

void foo()
{
    std::copy(
        personList.begin(),
        personList.end(),
        std::ostream_iterator(std::cout, " ")
        );
}

Note that this works with any pair of iterators, not only those from std::set<t>. std::copywill use your user-defined operator<<to print out every item inside the setusing this single statement.

请注意,这适用于任何一对迭代器,而不仅仅是来自std::set<t>. std::copy将使用您的用户定义operator<<打印出set使用此单个语句中的每个项目。

回答by Georg Fritzsche

You need to dereference the iterator:

您需要取消引用迭代器:

 std::cout << *location;

The convention of using the indirection or dereferencing operator to get the referenced value for an iterator was chosen in analogy to pointers:

选择使用间接或取消引用运算符来获取迭代器的引用值的约定类似于指针:

 person* p = &somePerson;
 std::cout << *p;

回答by Alex Spencer

it is a set::iterator

它是一个集合::迭代器

   for(it = output_set.begin(); it != output_set.end(); it++)
    {
        outstream_1 << *it << endl;
    }