C++中依据结构体成员变量对结构体向量进行排序的技术问询
bar_s by BarItem::value in Descending Order Hey there! Let's fix your sorting issue quickly. You don't need those iterators pointing directly to the value_t members—instead, we can tell std::sort exactly how to compare your BarItem objects based on their value field. Here's how to do it:
1. Core Idea: Custom Comparators for std::sort
The std::sort function lets you pass a custom rule (a comparator) to define the order of elements. For your goal (sorting so larger value values come first), we just need to write logic that checks if one BarItem's value is bigger than another's.
2. Method 1: Using a Standalone Comparison Function
First, add a helper function that compares two BarItems. Make sure to include the <algorithm> header for std::sort:
#include <algorithm> // Returns true if a should come before b (descending order by value) bool compareByValueDesc(const bcra::BarChart::BarItem& a, const bcra::BarChart::BarItem& b) { return a.value > b.value; }
Then use this function in your main code when calling sort:
int main() { bcra::BarChart m_barChart; // Fix: reference the bcra namespace! // ... (your file reading and bar_s population code) ... // Sort bar_s with our custom rule std::sort(bar_s.begin(), bar_s.end(), compareByValueDesc); }
3. Method 2: Using a Lambda Expression (More Concise)
If you don't want a separate function, you can pass a lambda directly to std::sort—this is cleaner for simple comparisons:
int main() { bcra::BarChart m_barChart; // ... (your existing code) ... // Sort with an inline lambda std::sort(bar_s.begin(), bar_s.end(), [](const bcra::BarChart::BarItem& a, const bcra::BarChart::BarItem& b) { return a.value > b.value; // Larger values come first } ); }
4. Quick Fixes for Your Code
- Namespace Correction: Your
BarChartclass lives in thebcranamespace, so you need to writebcra::BarChart(not justBarChart) inmainto avoid compilation errors. - Skip the Value Iterators:
std::sortworks with iterators to yourBarItemobjects directly—you don't need to point to thevaluemember itself. The comparator handles accessing that field for you.
内容的提问来源于stack exchange,提问作者diniz junior

