如何在 C++ 中对向量数组进行排序?

How to sort an array of vectors in c++?

我创建了一个向量数组。接受输入后我必须对它们进行排序,我想我需要使用比较器功能,但我不明白如何使用它。

int main()
{
    
    int  n, k;
    cin >> n >> k;
    vector<long long> times[4];
  
    for (int i = 0; i < n; ++i)
    {
        ll t, a, b;
        cin >> t >> a >> b;
        times[a * 2 + b].push_back(t);
    }

    cout << times[0].size();
    ***//i need to sort the whole of times[0] after this***
}

这取决于您需要排序的内容。

如果您想对内部数组进行排序,请使用这种方式进行排序。它对时间 [0] 进行排序。第二个版本带有自定义比较器

std::sort(times[0].begin(), times[0].end());
std::sort(times[0].begin(), times[0].end(), [](ll a, ll b){ return a < b; });

如果你需要对“times”数组进行排序,那么你可以用你自己的比较器这样写:

std::sort(std::begin(times), std::end(times), 
    [](const std::vector<ll>& a, const std::vector<ll>& b)
    {
        return a.size() < b.size();
    }
);

根据评论编辑:

如果字典排序顺序足够,那么您可以跳过自定义比较器:

std::sort(std::begin(times), std::end(times));

对于升序,

sort(times.begin(),times.end());

对于降序,

sort(times.begin(), times.end(), greater<int>()); 

另一种方式,

    void cmp(ll a, ll b) { 
      return a < b;  
    }

  // Use the below statement anywhere you want - 
    sort(times.begin(),times.end(),cmp);