遍历字符串的嵌套向量
我的代码中存在嵌套字符串向量的问题。它不打印字符串。
void foo(vector<vector<char const *> > const & vcp){
vector<vector<char const *> >::const_iterator i(vcp.begin());
vector<vector<char const *> >::const_iterator e(vcp.end());
for(; i != e; ++i){
vector<char const *>::const_iterator ci(i->begin());
vector<char const *>::const_iterator ce(i->end());
for(; ci != ce; ++ci)
cout<<*ci<<endl; //Not printing
}
}
int main(){
std::vector<vector<char const *> > vvcp(3);
std::vector<char const *> vcp(3);
vcp.push_back(string("abcd").c_str());
vcp.push_back(string("efgh").c_str());
vcp.push_back(string("ijkl").c_str());
vvcp.push_back(vcp);
vvcp.push_back(vcp);
foo(vvcp);
return EXIT_SUCCESS;
}
There's an issue in my code with nested vectors of strings. It is not printing the strings.
void foo(vector<vector<char const *> > const & vcp){
vector<vector<char const *> >::const_iterator i(vcp.begin());
vector<vector<char const *> >::const_iterator e(vcp.end());
for(; i != e; ++i){
vector<char const *>::const_iterator ci(i->begin());
vector<char const *>::const_iterator ce(i->end());
for(; ci != ce; ++ci)
cout<<*ci<<endl; //Not printing
}
}
int main(){
std::vector<vector<char const *> > vvcp(3);
std::vector<char const *> vcp(3);
vcp.push_back(string("abcd").c_str());
vcp.push_back(string("efgh").c_str());
vcp.push_back(string("ijkl").c_str());
vvcp.push_back(vcp);
vvcp.push_back(vcp);
foo(vvcp);
return EXIT_SUCCESS;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与向量无关。
您正在创建临时
std::string
对象,获取指向其基础数据的指针,并在字符串不再存在后尝试使用这些指针 。这是不允许的。(另外,将 '*x' 提供给 std::cout,其中 'x' 是 char const*,将仅打印 C 字符串的第一个字符。)
只需将字符串存储在向量中。这就是你应该如何使用它们。
.c_str()
的存在实际上只是为了让您可以使用旧版 C 代码。This has nothing to do with the vectors.
You are creating temporary
std::string
objects, getting pointers to their underlying data, and trying to use those pointers after the strings no longer exist. That is not allowed.(Also, feeding '*x' to std::cout, where 'x' is a char const*, would print only the first character of the C-string.)
Just store the strings in the vectors. That's how you're meant to use them.
.c_str()
really only exists so you can work with legacy C code.我确认@Karl。以C 风格更改代码:
I confirm @Karl. Change your code in C style: