简体   繁体   中英

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

I want to iterate through a string vector in c++. I want to open each item in the list with 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 . 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. Using const auto& rather than auto obviates a std::string copy.

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 .

A std::string is a type which is completely different from const char * . Hence, you need to get underlying character buffer stored in string. For that You must use method std::string::c_str() or std::string::data() whatever you like.

Do it like below (Inspired from other answers now using 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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