简体   繁体   中英

How do I get certain values inside of an Array?

I am doing a program which will calculate some stuff, for example I need to know how many employees are Female, It is on a file which I read and saved it on an Array of string. The data saved on the Array are F of Female, and M of male. How do I count how many F(Female) there are inside the Array? I already have everything set all I need to know is how to count the values inside an array, specific values inside it(Just the F) and not all values.

This is the code that reads the Gender(Used in the example):

File.open("Gender.txt");
    for(int i=0; i<100; i++){
        File >> gender[i];
    }

And this is the variable used to store them:

string gender[100];

Gender.txt File is like this:

F
F
M
F
M
M
F
F
F
F
M
M
F
M
F
F
M
F
F
M
F

One approach would be to use a std::vector<char> to store F , M or what else that will be in the file. A vector can grow dynamically so you just have to read from the file and push_back() into the vector . When the file has been completely read, The size() member function will tell you how many entries you read from the file.

  • Add #include <vector> to get access to std::vector
  • Declare std::vector<char> gender; in main to keep the result.
  • Declare a counter for female and male , initialize to zero.
  • Open the file.
  • Loop:
     char gen; while(File >> gen) { gender.push_back(gen); // if gen is an F, increase `female` // else if gen is an M, increase `male` }
  • When the whole file is read, you can print the stats:
     std::cout << "Female: " << female << '\n' << "Male: " << male << '\n' << "Other: " << (gender.size() - female - male) << '\n';

Use std::count_if of the algorithm header.

count_if( InputIt first, InputIt last, UnaryPredicate p );

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