如何循环读取TXT文件,按第一列分组计算对应第二列最小值?
Solution: Find Minimum Value per Group in C++
First, let's break down what you need to do: your data file has rows where the first column cycles through values from -180 to 180 in steps of 5, and the second column has corresponding numeric values. You want to find the smallest second-column value for each unique first-column entry, then output those pairs in order.
Here's how to modify your existing code with loops and a tracking structure to make this happen:
Step-by-Step Breakdown
- Set up a way to track minima: Since your first-column values are predictable (-180, -175, ..., 180), an array (or vector) is the most efficient way to store the minimum value for each key. Each index in the array maps directly to one of your first-column values.
- Process every line in the file: Loop through each row, updating the minimum value for the corresponding first-column key whenever you find a smaller second-column value.
- Output the results: Loop through your tracking structure in order of the first-column values and print each key along with its minimum.
Complete Code Example
#include <iostream> #include <fstream> #include <limits> #include <vector> // For safer memory management using namespace std; int main() { // Define your first column range and step const int start_val = -180; const int end_val = 180; const int step_val = 5; // Calculate how many unique first-column values there are int num_entries = (end_val - start_val) / step_val + 1; // Initialize a vector to store minima (start with the largest possible double value) vector<double> min_values(num_entries, numeric_limits<double>::max()); // Open your data file (replace "your_data.txt" with your actual file path) ifstream input_file("your_data.txt"); if (!input_file.is_open()) { cerr << "Oops! Couldn't open the data file. Check the path." << endl; return 1; } // Read each line and update the minima int first_col; double second_col; while (input_file >> first_col >> second_col) { // Calculate the index for this first-column value int index = (first_col - start_val) / step_val; // Make sure the value is within your expected range if (index >= 0 && index < num_entries) { if (second_col < min_values[index]) { min_values[index] = second_col; } } else { cerr << "Warning: Skipping invalid first-column value: " << first_col << endl; } } // Close the file when done input_file.close(); // Print the results neatly cout << "First Column | Minimum Second Column" << endl; cout << "-----------------------------------" << endl; for (int i = 0; i < num_entries; ++i) { int current_key = start_val + (i * step_val); cout << current_key << "\t\t" << min_values[i] << endl; } return 0; }
Key Details to Note
- Vector vs. Raw Array: We used a
std::vectorhere because it handles memory automatically (no need to manually delete it), which is safer and more modern C++ practice. - Initialization: We start each minimum value at
numeric_limits<double>::max()(the largest possible double value) so any valid second-column value will immediately replace it. - Error Handling: The code checks if the file opens correctly and warns about unexpected first-column values, making it more robust to messy data.
- Efficiency: Using a vector means lookups and updates are O(1) time, so this will handle large data files quickly.
内容的提问来源于stack exchange,提问作者Masoom Singh
相关产品推荐
相关产品推荐

