int index = 2;
auto it = mymap.begin();
for(int i = 0; i < index && it != mymap.end(); ++i)
++it;
if(it != mymap.end())
std::cout << it->first<<" =>"<< it->second << '\n';
else
std::cout << "not found";
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <stdlib.h>
usingnamespace
std;
int main() {
string x;
int y,k;
map<string,int>mymap;;
ifstream in("h.txt");
if (!in) {
cout<< "Unable to open h.txt file" <<endl;
return 1;
}
while (in >> x >> y){
mymap[x] = y;
}
int index = 2;
auto it = mymap.begin();
for(int i = 0; i < index && it != mymap.end(); ++i)
++it;
if(it != mymap.end())
std::cout << it->first<<" =>"<< it->second << '\n';
else
std::cout << "not found";
cin >> k;
return 0;
}
then I got
1 2 3 4 5 6 7
In function `int main()':
24 ISO C++ forbids declaration of `it' with no type
24 cannot convert `std::_Rb_tree_iterator<std::pair<const std::string, int> >' to `int' in initialization
25 no match for'operator!=' in 'it != (&mymap)->std::map<_Key, _Tp, _Compare, _Alloc>::end [with _Key = std::string, _Tp = int, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, int> >]()'
27 no match for'operator!=' in 'it != (&mymap)->std::map<_Key, _Tp, _Compare, _Alloc>::end [with _Key = std::string, _Tp = int, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, int> >]()'
base operand of `->' is not a pointer
28 base operand of `->' is not a pointer
Well, move loop and printing in own function and call it with different parameters
(alternatively you can print values from the loop body if you would check if it has enough elements beforehand.)
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <stdlib.h>
usingnamespace
std;
int main() {
string x;
int y,k;
map<string,int>mymap;;
ifstream in("h.txt");
if (!in) {
cout<< "Unable to open h.txt file" <<endl;
return 1;
}
while (in >> x >> y){
mymap[x] = y;
}
int m=0;
asd:
int index = m + 0;
for (int j=0;j<2;j++){
map<string, int>::iterator it = mymap.begin();
for(int i = 0; i < index && it != mymap.end(); ++i)
++it;
index++;
if(it != mymap.end())
std::cout << it->first<<" =>"<< it->second << '\n';
else
cout << "not found";}
m = m + 2;
cin >> k;
goto asd;
return 0;
}
Now could you please tell how I can do the next
I need to assign the value of the second which is integer to a variable each time. so if the first second is 8 I need a=8 and if the second second is 4 I need b=4 so I can use them later