C++按字母顺序对带有常量变量的结构向量进行排序



你好,我想知道是否可以做这样的事情?//谢谢!:(

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。自定义排序函数的参数通常保持为const,因为它们不应该是可修改的。这是一种确保安全编码实践的模式

此外,如果您使用C++,我建议使用std::string而不是char*,因为std::字符串是一种更干净、更安全的方法,因为它减轻了程序员的内存管理负担。

看看工作实现,不使用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不能是变量。它是一个常数,用于定义:(

您在代码中编写的向量不能以这种方式构建。我不明白你想用"排序"函数做什么,我写了以下代码,也许它会有所帮助:

#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中,它引入了三方比较,并且您可以通过一行声明Default比较。非常方便。不幸的是,还没有编译器实现这个功能。

现在,您必须手动定义比较器

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

并将其传递给std::sort

最新更新