0

その要素を使用してユーザー定義クラスのベクトルをソートする方法を知る必要があります。int値を返すgetXメソッドとgetYメソッドを持つ「coordinates」というクラスがあるとします。ベクトル「vectorPointTwoDvcP2D(5);」の配列を作成しました。

 class coordinates {
 int getX();
 int getY();

  )

ここで問題は、1)getX()を使用してベクトル「vcP2D」を並べ替え、昇順で並べ替える必要がある2)ユーザーがx座標として「2」を入力したとします。そして、その情報を使用して、どのベクトルに2が含まれているかを見つける必要があります

ご意見をお聞かせください

4

2 に答える 2

6

これは行います:

std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d){ return c.getX() < d.getX(); });

のバイナリ述語としてC++11Lambda式を使用しstd::sortます。

簡単なデモンストレーション

#include <algorithm>
#include <vector>

#include <iostream>

struct coordinates
{
  int x;
  int y;
};

int main()
{
  std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} };

  std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.x < d.x; });

  std::cout << "sorted by x values, values of \"x\": " << v[0].x << " " << v[1].x << " " << v[2].x << "\n";

  std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.y < d.y; });

  std::cout << "sorted by y values, values of \"x\": "  << v[0].x << " " << v[1].x << " " << v[2].x << "\n";
}

同じ方法で要素を見つける方法のデモ

#include <algorithm>
#include <vector>

#include <iostream>

struct coordinates
{
  int x;
  int y;
};

int main()
{
  std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} };

  auto result = std::find_if(v.begin(), v.end(), [](const coordinates& c){ return c.x == 1 && c.y == 5; });
  if(result != v.end())
    std::cout << "point (1,5) is number " << std::distance(v.begin(), result)+1 << " in the vector.\n";
  else
    std::cout << "point (1,5) not found.\n";
 }

ソートされたベクトルを検索する場合std::binary_searchは、比較関数(上記と同じstd::sort)を使用することができます。また、その要素にイテレータを与えるのではなく、trueまたはだけを与えますfalse

于 2012-10-07T18:16:53.863 に答える
3

operator< ()またはバイナリ述語を使用して、要素に厳密な弱順序を定義してから、を使用する必要がありますstd::sort()

最も簡単なアプローチは、以下を作成することですoperator<()

bool operator< (coordinates const& c0, coordinates const& c1) {
    // return a suitable result of comparing c0 and c1 such that operator<()
    // become a strict weak order
}

これで、ソートするために必要なのはstd::vector<coordinates>を使用することだけstd::sort()です。特定のオブジェクトを見つけるには、を使用しますstd::lower_bound()

于 2012-10-07T17:34:05.913 に答える