开发者

C++ sort a vector of struct, but one element is missing [closed]

开发者 https://www.devze.com 2022-12-07 18:42 出处:网络
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code nece
Closed. This question needs debugging details. It is not currently accepting answers.

Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.

Closed 1 hour ago.

开发者_Python百科 Improve this question

I have a struct (name, val1, val2) and want to sort by val2, but how come it is always missing one element? Below is my code:

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    struct sub
    {
        std::string name;
        int val1; 
        int val2; 
    };

    std::vector< sub > vec; 
    vec.push_back( { "first", 2, 3 } );
    vec.push_back( { "second", 2, 1 } );
    vec.push_back( { "Third", 1, 5 } );
    vec.push_back( { "Forth", 1, 8 } );
    vec.push_back( { "Fifth", 1, 10 } );
     
    std::sort( vec.begin(), vec.end(), []( const sub & a, const sub & b )
    {
        return a.val2 > b.val2;
    } );

    for ( auto vec1 = vec.begin(); vec1 != vec.end(); ++vec1 )
    {
        std::cout << vec1->name << std::endl; 
    }

    return 0;
}

For result, I got:

Forth
Third
first
second

Why is Fifth not showing ?

0

精彩评论

暂无评论...
验证码 换一张
取 消