
This code uses the vector container I have used before with another example, please check or search in my blog.
We can store two value items using a "tuple". The tuple class is simple, you declare a list of the types of items in the tuple object in the declaration between the angle brackets. So the tuple<string, int> declaration says that the object will hold a string and an integer.
The make_tuple function is provided by the C++ Standard Library and will create a tuple object containing 2 values.
The push_back function will put the item into the vector container.
You can hold a lot of things in the tuple function
Ex: tuple<string, int, string>;
Ex: tuple<char, string, int, string>;
Finally, the "auto" keyword means that that compiler should create a variable with the type of the data that is assigned to it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <tuple> | |
using namespace std; | |
int main() | |
{ | |
vector<tuple<int, string, string>> mystudents; | |
mystudents.push_back(make_tuple(1, "John", "New York")); | |
mystudents.push_back(make_tuple(2, "Marry", "Houston")); | |
mystudents.push_back(make_tuple(3, "Paul", "Boston")); | |
mystudents.push_back(make_tuple(4, "Peter", "Cincinnati")); | |
//Using without auto keyword | |
for (tuple<int, string, string> student : mystudents) | |
{ | |
cout << get<0>(student) << " " << get<1>(student) << " " << get<2>(student) << endl; | |
} | |
//Using auto keyword | |
for (auto student : mystudents) | |
{ | |
cout << get<0>(student) << " " << get<1>(student) << " " << get<2>(student) << endl; | |
} | |
system("pause"); | |
return 0; | |
} |
No comments:
Post a Comment