简体   繁体   中英

How to initialize pair<vector<pair<bool,int>>,vector<pair<bool,int>>> in C++11

I'd like to initialize:

pair<vector<pair<bool,int>>,vector<pair<bool,int>>> pvp;

so that for all i:

pvp.first[i].first = true;

and

pvp.second[i].first = false;

I know that you could do this with a loop but isn't there any faster way like an initialization for a vector ?

Sorry, I do not have a direct answer to the question, but I do not see the the question as the real problem.

Generic data structures are great, but maybe, consider a few classes, instead. That way the individual class constructers can handle the initializations as needed (in smaller pieces).

The initialization syntax would be:

pvp{ vector<pair<bool, int>>(5, { true, 0 }), vector<pair<bool, int>>(5, { false, 0 }) };

Now, you didn't specify any length of the array (or what the integer should be), but here's the full approach:

#include <tuple>
#include <vector>
#include <iostream>

using namespace std;

int main(){

    pair<vector<pair<bool, int>>, vector<pair<bool, int>>> pvp{ vector<pair<bool, int>>(5, { true, 0 }), vector<pair<bool, int>>(5, { false, 0 }) };

    for (auto i : pvp.first){
        cout << (i.first ? "true" : "false") << '\n';
    }
    for (auto i : pvp.second){
        cout << (i.first ? "true" : "false") << '\n';
    }

    return 0;
}

Output:

 true
 true
 true
 true
 true
 false
 false
 false
 false
 false

As already mentioned, this implementation is too complex for a simple human reader to understand. Separate it into smaller pieces, though.

Consider using typedefs to make the code easier to read.

using MyPair = pair<bool,int>;
using MyPairs = vector<MyPair>;
pair<MyPairs,MyPairs> pvp{MyPairs{make_pair(true,10)},
                          MyPairs{make_pair(false,11)}};

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