编写一个函数,无论类型如何,都打印 STL 向量的每个元素

发布于 2024-09-18 01:47:32 字数 457 浏览 2 评论 0原文

我尝试使用这段代码,但它不起作用

template <class T>
void display(vector<T> vec)
{
  vector<T>::iterator MyIter;
  for(MyIter=vec.begin();MyIter!=vec.end();MyIter++)
    cout<<*MyIter<<" ";
  cout<<endl;
}

我的意思是是否有一种方法可以避免为每种类型 T (int、char、string)创建函数。我只使用 T 的内置类型。

这是我编译程序时的错误消息

10 C:\Documents and Settings\ASPIRE\Desktop\perms.cpp expected `;' before "MyIter" 

I tried with this piece of code but it didn't work

template <class T>
void display(vector<T> vec)
{
  vector<T>::iterator MyIter;
  for(MyIter=vec.begin();MyIter!=vec.end();MyIter++)
    cout<<*MyIter<<" ";
  cout<<endl;
}

I mean if there's a way of avoid making a function for each type T (int, char, string). I'm using only builtin types for T.

This is the error message when I compile the program

10 C:\Documents and Settings\ASPIRE\Desktop\perms.cpp expected `;' before "MyIter" 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜心小果奶 2024-09-25 01:47:33

您缺少变量定义MyIter前面的typename,即它应该是typename vector::iterator MyIter;

You are missing the typename infront of the variable definition MyIter i.e. it should be typename vector<T>::iterator MyIter;

静赏你的温柔 2024-09-25 01:47:33

您能更清楚地了解这段代码如何不起作用吗?

它依赖于 T::operator<< 的存在。 - 如果您在代码中使用的任何实例化类型/类 T 都不存在,则代码将无法编译。对于内置类型,此代码可以正常工作。如果您将其用于您自己类型的向量,那么您将必须实现运算符<<每个人都可以做到这一点。

顺便说一句,使用++MyIter,它的效率更高。

Can you be more clear on how this code did not work?

It relies on the existence of T::operator<< - if that is not present for any instantiating type/class T that you use in your code, the code will not compile. For builtin types this code would work OK. If you are using this for vector of your own types then you would have to implement operator<< for each for this to work.

btw use ++MyIter, it's more efficient.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文