有谁知道为什么
#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/