我没有错误,但我的输出不是我想要的。我想让'stuff + i'成为向量的输入。但我的输出只是我最初的“东西”变量 - 1个字符。
stuff
tuff
uff
ff
f
/0
/0
gello?
ello?
llo?
gello?
代码:
#include <iostream>
#include <string>
#include <vector>
struct Playlist
{
std::string name;
} ;
int main()
{
std::vector<Playlist> playlist;
std::cout << "Input 10 stuff" << std::endl;
for( int i = 0; i < 10; ++i )
{
Playlist ok;
ok.name = "stuff " + i;
playlist.push_back( ok );
std::cout << playlist.size() << std::endl;
}
std::vector<Playlist>::iterator iter = playlist.begin();
while( iter != playlist.end() )
{
std::cout << iter->name << std::endl;
++iter;
}
std::cout << "gello?" << std::endl;
std::vector::iterator iter = playlist.begin();
while( iter != playlist.end() ) { std::cout << iter->name << std::endl; ++iter; }
std::cout << "gello?" << std::endl;
return 0;
}
答案 0 :(得分:4)
更改此声明
ok.name = "stuff " + i;
到
ok.name = "stuff " + std::to_string( i );
至于陈述
ok.name = "stuff " + i;
然后在右侧使用指针算术。字符串文字转换为指向其第一个元素的指针。所以
"stuff " + 0 returns pointer to character 's'
"stuff " + 1 returns pointer to character 't'
"stuff " + 1 returns pointer to character 'u'
等等。
所以第一个push_back处理字符串“stuff”。第二个 - 带字符串“tuff”,第三个 - 带字符串“uff”,依此类推。
结果是程序有未定义的行为,因为sizeof(“stuff”)小于10并且你试图访问超出字符串文字的内存。