I need to assign each line from the file a number in ascending order and by this number as a key in the map work with a separate line.

The second question is how to use string in stl so that it would be something like an array and refer to each element of the array as word [i].

#include "stdafx.h" #include <iostream> #include <fstream> #include <string> #include <map> int main() { setlocale (LC_ALL, ".866"); setlocale (LC_ALL, ".1251"); std::ifstream ifs("file.txt"); std::map<std::string, int> table; std::string word; while(ifs >> word) { table[word]++; } for(std::map<std::string, int>::iterator it = table.begin(); it != table.end(); it++) { std::cout << it->first << " " << it->second << std::endl; } system("pause"); return 0; } 
  • This is the question where? If to what I wrote - then access to the values ​​is made by key, as an index access to the example: to get the row in the second position, you need to refer to table [1] (numbering from 0). - Kozlov Sergei

1 answer 1

What was the problem? You have everything written correctly, but based on your requirements, it is enough to simply swap the key and value:

 std::map<int, std::string> table; 

And then we do the following in a loop:

 size_t i=0; while(ifs >> word) { table[i++]=word; } 

For correct and complete work with strings, I recommend connecting string.h, string.

  • what's the point in map <int, T>? I think it’s more logical to use vector <T> in such cases - andrybak
  • The person understands how to work with hash tables, respectively, and the answer is. Of course I have nothing against a vector or array. - Kozlov Sergei
  • Can you tell me how I can refer to a specific line from the file? - gvenog
  • doublepost, the answer is above: table [1] - referring to the second line read from the file - Kozlov Sergei
  • thanks, I will try - gvenog