【发布时间】:2015-05-24 19:43:19
【问题描述】:
我目前正在学习 C++,我有以下工作代码:
int main(int argc, char** argv) {
map<unsigned int, list<mpz_class>> otp;
// .....
for(auto it1 = otp.begin(); it1 != otp.end(); ++it1) {
bool first = true;
for(auto it2 = it1->second.begin(); it2 != it1->second.end(); ++it2) {
if (!first) {
cout << ", ";
} else {
first = false;
}
cout << *it2;
}
}
}
我想把列表的打印放到一个函数中。
这是我的尝试:
void prnt_list(vector it, ostream outstr, string delimiter) {
bool first = true;
for(auto it2 = it.begin(); it2 != it.end(); ++it2) {
if (!first) {
outstr << delimiter;
} else {
first = false;
}
outstr << *it2;
}
}
int main(int argc, char** argv) {
map<unsigned int, list<mpz_class>> otp;
// .....
for(auto it1 = otp.begin(); it1 != otp.end(); ++it1) {
prnt_list(it1->second, cout, ", ");
}
)
它不编译:
error: variable or field 'prnt_list' declared void
error: missing template arguments before 'it'
error: expected primary-expression before 'outstr'
error: expected primary-expression before 'delimiter'
然后我尝试了这个:
template <typename T>
void prnt_list<T>(vector<T> it, ostream outstr, string delimiter) {
...
}
但它也不起作用。
另外,我也不喜欢强制模板,因为我想允许任何向量。如果我能以某种方式使用auto 关键字,那就更舒服了。
【问题讨论】:
-
尝试
ostream&而不是ostream。 -
@VladfromMoscow
std::vector可能。 -
@VladfromMoscow
std::vector。我认为这是我需要得到.begin和.end() -
@milleniumbug C++ 中是否存在从 std::list
到 std::vector 的隐式转换? -
std::copy(otp.begin(), otp.end(), infix_ostream_iterator
(std::cout, ", "));