简体   繁体   中英

C++ For loop for two vector<string> and it's position to string

using namespace std;

int main() {
    vector<string> data={"Hello World!","Goodbye World!"};
    for (vector<string>::iterator t=data.begin(); t!=data.end(); ++t) 
    {
        cout<<*t<<endl;
    }
    return 0;
}

But I have two vectors and I need to convert their values to strings at certain position, like this:

vect = lineget3(nazev_souboru);
vect2 = lineget4(nazev_souboru);

for (a = vect.begin(); a < vect.end(); a++)
{
    string str = *a;
    string str2 = *b;?
}

And I dont know how to make str2 = *b (position of vect2). How to make for loop for two vectors at certain position?

I cant make this

for (a = vect.begin(); a < vect.end(); a++)
{
    for (b = vect2.begin(); b < vect2.end(); b++)
    {
        string str = *a;
        string str2 = *b;
    }
}

I need only one loop for this. Thank you.

If the vectors have the same length you can do:

for (auto a = vect.begin(), b = vect2.begin(); a < vect.end() && b < vect2.end(); ++a, ++b) {
    string str = *a;
    string str2 = *b;
}

If they have different size, it won't work the loop will not iterate over all elements of the larger vector.

You can use ranges::view::zip to combine a pair of ranges into one, and then use structured bindings to split the elements

for (auto [a, b] : ranges::view::zip(vect, vect2))
{
    // use a and b
}

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