簡體   English   中英

C++ 按字母順序對具有 const 變量的結構向量進行排序

[英]C++ Sorting vector of structs with const variables alphabetically

您好,我想知道是否可以做這樣的事情? // 謝謝: :)

 struct PET { const char* pet; const int age; }; bool Sort(const PET& first, const PET& second) { return first.pet < second.pet; } void Foo(const std::vector<PET> pets) { std::sort(pets.begin(), pets.end(), Sort); /* Does not work */ std::cout << pets[0].pet; std::cout << pets[0].age; }

我完全同意@Ulrich Eckhardt。

您無法對向量進行排序,因為向量的元素不可分配。

我認為,您可能對const的用法感到困惑。

無需將結構變量設為const 自定義排序 function 的參數一般保持為const ,因為它們不應該是可修改的。 這是一種確保安全編碼實踐的模式。

另外,如果您使用的是 C++,我建議使用 std::string 而不是 char*,因為 std::string 是一種更清潔、更安全的 go 方式,因為它消除了程序員對 ZCD69B4957F08CD818DZBBF3D619 管理的負擔。

看看工作實現,不使用 const:

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

struct PET
{ 
    std::string name;
    int age;
};

bool compare(const struct PET& a, const struct PET& b){

    return (a.name.compare(b.name) <= 0) ? true : false;        
}

int main(){

    std::vector<struct PET> vec(3);

    vec[0].name = "dog";
    vec[0].age = 3;

    vec[1].name = "cat";
    vec[1].age = 1;

    vec[2].name = "bird";
    vec[2].age = 2;

    sort(vec.begin(), vec.end(), compare);

    for(int i=0;i<3;i++){

        std::cout<<vec[i].name<<" "<<vec[i].age<<std::endl;
    }
    return 0;

}

正如@Deepak Tatyaji Ahire 和@Ulrich Eckhardt 所說,你不能做你在代碼中寫的東西。

const int不能是變量。 它是一個用於定義的常量:)

您在代碼中編寫的向量不能以這種方式構建。 我不明白你想用“排序”function 做什么,我寫了以下代碼,也許它可以幫助:

#include<iostream>
#include<vector>

struct PET
{
 const char* pet;
 int age;

 PET(const char* c, int a) : pet(c) , age(a) {}

};

void  Foo(PET &p, std::vector<PET> &v)
{
  v.push_back(p);
  /*do something here if needed*/

}

int main()
{
    std::vector<PET> vect;
    PET cat("Cat", 5);
    PET dog("Dog", 10);
    PET bird("Bird", 2);
    Foo(cat, vect);
    Foo(dog, vect);
    Foo(bird, vect);
    /*this is not elegant, you could define a function that give a list of
    ({Animal, age},...) to vector and then pushes back all these elements to the vector*/
    for(int i=0; i<3; i++) std::cout<< vect[i].pet << ' ' << vect[i].age << std::endl; //std::cout << vect; if you are using an operator << overload
    /*to overload the << operator in order to able to print the vector of struct PET:

std::ostream & operator << (std::ostream &os, std::vector<PET> &p)
{
     os << "<";
    for (int i = 0; i < p.size(); i++) {
        os << p[i].pet;
        os << ", ";
        os << p[i].age;
        if (i != p.size() - 1)
            os << " - ";
    }
    os << ">\n";
    return os;
}

    */

    return 1;
}

AFAIK,沒有定義比較器就無法直接比較結構。

盡管在 C++20 中,它引入了三向比較,並且您可能被允許通過單行聲明 默認比較 很方便。 不幸的是,還沒有編譯器實現這個特性。

現在,您必須手動定義比較器

inline bool cmp(const PET &lhs, const PET &rhs)
{
    return std::strcmp(lhs.pet, rhs.pet)<0;
}

並將其傳遞給std::sort

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM