vector<pair<const string, int>> v{ {"XXX", 0}, {"YYY", 0}, {"ZZZ", 0} };
for (size_t i = 0; i < v.size(); i )
{
cout << v[i].second << endl;
}
Do I have to explicitly assign 0 for every element? Is there a convenient way to do this?
PS: To replace 0
with {}
won't help.
CodePudding user response:
Not too much good way, I give this solution,
auto my_make_pair = [](string&& s)->pair<const string, unsigned> {
return { s,0 };
};
vector<pair<const string, int>> v{ my_make_pair("XXX"), my_make_pair("YYY"), my_make_pair("ZZZ") };
for (size_t i = 0; i < v.size(); i )
{
cout << v[i].second << endl;
}
CodePudding user response:
When you want elements in a vector
to be initialized with default values
, just declare your vector using a constructor with one parameter which is the size of your vector:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
constexpr uint8_t number_of_pairs{3}; // desired size
vector<pair<const string, int>> v(number_of_pairs);
for (size_t i = 0; i < v.size(); i )
{
cout << v[i].second << endl;
}
return 0;
}