繁体   English   中英

列出C ++中的迭代器问题?

[英]list iterator problem in c++?

#include <iostream>
#include <list>
#include <string>
using namespace std;

// Simple example uses type int

main()
{
   list<string > L;
   L.push_back("test");              // Insert a new element at the end

 L.push_back("testinggggg"); 
 L.push_back("example"); 
   list<string>::iterator i;

   for(i=L.begin(); i != L.end(); ++i) {
       string test = *i;
       cout << test;
   }
   return 0;
}

如果使用上述程序,并且将string test=*i更改为cout << *i << " ";则不会得到任何输出cout << *i << " "; 有用。 这是什么问题?

这甚至不应该编译(在最近的g ++上也不应该编译)。

i是一个list<int>的迭代器,所以*iint类型。 如果将此分配给这样的string

string test=*i;

编译器将寻找从intstring的转换。 在标准库中没有定义这种转换。

您的最后一个for循环试图将字符串test设置为整数值。

您应该尝试cout << * i << endl;

它为我工作并产生输出:

testtestingggggexample

您会在单词和endl之间缺少空格,但是输出如您所愿。

jkugelman$ g++ -Wall -o iterator iterator.cpp 
iterator.cpp:8: warning: ISO C++ forbids declaration of ‘main’ with no type
jkugelman$ ./iterator 
testtestingggggexamplejkugelman$ 

为我工作。 我得到了这个输出

testtestinggggg示例

我使用的是Suse g ++ 3.4.3版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM