打印一组的 C++ 函数

标签 c++

有谁知道为什么

#include <set>
#include <string>
#include <iostream>

template <typename T>
std::string set2Str(const std::set<T> & S)
{
    std::string retstr = "{";
    typename std::set<T>::const_iterator it(S.begin()), offend(S.end());
    if (it != offend)
        retstr.push_back(*it++);
    while (it != offend)
    {
        retstr.push_back(',');
        retstr.push_back(*it++);
    }
    retstr.push_back('}');
    return retstr;
}

int main()
{
    std::set<int> mySet = {1, 5, 9, 69};
    std::cout << set2Str(mySet);
}

正在输出

{,,   ,E}

???

还有,是否有更优雅的方式来编写函数set2Str?逗号的栅栏问题使我的程序变得丑陋。

最佳答案

当你的算法执行此操作时:

retstr.push_back(*it++);

输入到目标字符串中的值将被视为(并在可能的情况下转换为)char。但 {1, 5, 9, 69} 不包含 char;它包含int。结果是将它们视为 ASCII 代码点, See this table ,并特别注意其中每个字符的 dec 值。例如,请注意 E 的值。

这是 std::ostringstream 的众多用途之一,其优点是允许可以表示任何可以写入字符流的内容,包括利用自定义插入运算符。

#include <iostream>
#include <sstream>
#include <string>
#include <set>
#include <tuple>

template<typename T, typename... Args>
std::string set2str(const std::set<T,Args...>& obj)
{
    std::ostringstream oss;

    oss << '{';
    auto it = obj.cbegin();
    if (it != obj.cend())
    {
        oss << *it++;
        while (it != obj.cend())
            oss << ',' << *it++;            
    }
    oss << '}';
    return oss.str();
}

// custom class to demonstrate custom insertion support
class Point
{
    friend std::ostream& operator <<(std::ostream& os, const Point& pt)
    {
        return os << '(' << pt.x << ',' << pt.y << ')';
    }

private:
    double x,y;

public:
    Point(double x, double y) : x(x), y(y) {}

    // used by std::less<> for set ordering
    bool operator <(const Point& pt) const
    {
        return std::tie(x,y) < std::tie(pt.x,pt.y);
    }
};

int main()
{
    std::set<int> si = { 1,2,3,4,5 };
    std::set<double> sd = { 1.1, 2.2, 3.3, 4.4, 5.5 };
    std::set<char> sc = { 'a', 'b', 'c', 'd', 'e' };
    std::set<unsigned> empty;

    std::cout << set2str(si) << '\n';
    std::cout << set2str(sd) << '\n';
    std::cout << set2str(sc) << '\n';
    std::cout << set2str(empty) << '\n';

    // using custom class with implemented ostream inseter
    std::set<Point> pts { {2.2, 3.3}, {1.1, 2.2}, {5.5, 4.4}, {1.1, 3.3} };
    std::cout << set2str(pts) << '\n';

    return EXIT_SUCCESS;
}

输出

{1,2,3,4,5}
{1.1,2.2,3.3,4.4,5.5}
{a,b,c,d,e}
{}
{(1.1,2.2),(1.1,3.3),(2.2,3.3),(5.5,4.4)}

关于打印一组的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24043968/

相关文章:

c++ - 为什么我不能在这个专门的函数模板中将字符串文字传递给 const char* const&

c++ - 使用 libav 从内存中解码视频文件

c++ - 为什么在 Visual Studio 中使用 LLVM+Clang 时未定义 __clang__?

c++ - 高效获取 std::*_heap 的第二个元素

c++ - 如何更改以 50 为步长传递一些整数值到 C++ 代码

c++ - 是否可以在不编写复制构造函数的情况下在 main 中的构造函数之间进行选择?

c++ - 带有 STL 容器的 OpenMP 嵌套循环

c++ - std::string.find_first_not_of,意外的返回值

c++ - 如何对用户定义类型使用 BOOST_CHECK_CLOSE

c++ - 指向 void 函数中的类的指针