简体   繁体   English

我怎样才能在c ++中迭代字符串向量?

[英]How am I able to iterate through a string vector in c++?

I want to iterate through a string vector in c++. 我想在c ++中迭代字符串向量。 I want to open each item in the list with fopen. 我想用fopen打开列表中的每个项目。

const char *filep //fopen needs a constant char pointer.
for (vector<string>::iterator it = filelist.begin(); it != filelist.end(); it++)
{
    filep = (const char *)it; //This isn't working. How can I fix this
    fopen(filep, "rb"); 
}

You should have used it->c_str() as it is essentially a pointer to the element in the std::vector . 您应该使用it->c_str()因为it本质上是指向 std::vector元素的指针 But for an easier life use 但为了更轻松的生活使用

for (const auto& s : filelist){
    // s is a const reference to an element in filelist
    // use s.c_str() if you need the character buffer
}

This is valid from C++11 onwards. 从C ++ 11开始,这是有效的。 Using const auto& rather than auto obviates a std::string copy. 使用const auto&而不是auto避免使用std::string副本。

Change this: 改变这个:

filep = (const char *)it;

to this: 对此:

filep = it->c_str();

However, you do extra, unnecessary steps, since you could just do this instead: 但是,你做了额外的,不必要的步骤,因为你可以这样做:

for (vector<string>::iterator it = filelist.begin(); it != filelist.end(); it++)
    fopen(it->c_str(), "rb"); 

which reduces the number of lines of your code to just two, and doesn't use an extra pointer. 这会将代码行数减少到只有两行,并且不会使用额外的指针。


PS: A more modern approach can be found in Bathsheba's answer , or use the auto&& approach . PS:在Bathsheba的答案中可以找到更现代的方法,或者使用auto&&方法

A std::string is a type which is completely different from const char * . std::string是一种与const char *完全不同的类型。 Hence, you need to get underlying character buffer stored in string. 因此,您需要获取存储在字符串中的基础character buffer For that You must use method std::string::c_str() or std::string::data() whatever you like. 为此你必须使用方法std::string::c_str()std::string::data()

Do it like below (Inspired from other answers now using range-based for-loop ), 就像下面这样(灵感来自现在使用range-based for-loop其他答案),

const char *filep //fopen needs a constant char pointer.
for (auto & str : filelist)
{
    filep = str.c_str();
    fopen(filep, "rb"); 
}

create a method getstring in which you will return the string. 创建一个方法getstring,您将在其中返回该字符串。

for(unsigned int i=0; i<iterator.size();i++){
cout << iterator[i]->getstring()<<endl;
}

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

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