简体   繁体   中英

How do I access the index & object from a boost::container::vector<std::string>::iterator?

I'm a boost newbie. How do I access the object from an iterator? I have something like:

boost::container::vector<std::string>::iterator plitr = myvec.begin();
while (plitr != myvec.end()){
    std::cout << "data at index[" << plitr - myvec.begin() << "]: " << plitr->x <<std::endl;
plitr++;
}

But I realize that plitr->x does not exist nor am I sure if the index can be calculated the way I think. Can anyone help?

The usage of boost::vector is identical to std::vector . Calculating the index hence works the way you showed, because the iterator fulfills random access criteria. Concerning access to the object, you want to dereference the iterator. Change your loop to

while (plitr != myvec.end()){
    std::cout << "data at index[" << plitr - myvec.begin() << "]: " << *plitr <<std::endl;
    plitr++;
}

and it will work (note the *plitr , that't the dereferencing part). Just as a side note, using a range based for loop to access every std::string in myvec might be more convenient here:

for (auto&& str : myvec)
    std::cout << str << std::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