0

アルファベット順に並べ替えたいベクトルがあります。1 つのインデックス値でアルファベット順に並べ替えることができましたが、それを行うと、ベクトル全体ではなく、そのインデックスの順序のみが変更されます。順序の変更をベクトル全体に適用するにはどうすればよいですか? これは私が実行している現在のコードです:

std::sort (myvector[2].begin(), myvector[2].end(), compare);

bool icompare_char(char c1, char c2)
{
  return std::toupper(c1) < std::toupper(c2);
}

bool compare(std::string const& s1, std::string const& s2)
{
  if (s1.length() > s2.length())
    return true;
  if (s1.length() < s2.length())
    return false;
  return std::lexicographical_compare(s1.begin(), s1.end(),
                                      s2.begin(), s2.end(),
                                      icompare_char);
}

このベクトルの一般的な構造は vector[row][column] です。

| One | Two | Three |
|  1  |  2  |   3   |
|  b  |  a  |   c   |

たとえば、ベクトルがある場合:

myvector[0][0] = 'One' AND myvector[2][0]='b'
myvector[0][1] = 'Two' AND myvector[2][1]='a'
myvector[0][2] = 'Three' AND myvector[2][2]='c'

| One | Two | Three |
|  1  |  2  |   3   |
|  b  |  a  |   c   |

そして、私はそれを並べ替えます:

myvector[0][0] = 'One' AND myvector[2][0]='a'
myvector[0][1] = 'Two' AND myvector[2][1]='b'
myvector[0][2] = 'Three' AND myvector[2][2]='c'

| One | Two | Three |
|  1  |  2  |   3   |
|  a  |  b  |   c   |

私が欲しいものではありません:

myvector[0][0] = 'Two' AND myvector[2][0]='a'
myvector[0][1] = 'One' AND myvector[2][1]='b'
myvector[0][2] = 'Three' AND myvector[2][2]='c'

| Two | One | Three |
|  2  |  1  |   3   |
|  a  |  b  |   c   |

私は良いアプローチを探しましたが、うまくいくものを見つけることができませんでした...私は次のようなことを考えていました:

std::sort (myvector.begin(), myvector.end(), compare);

次に、比較関数内で 3 番目のインデックスの並べ替えを処理して、ベクトル全体が編集されるようにします...しかし、データを渡すときに、関数の順序を変更しただけで、最上位レイヤーを変更しなかったか、エラーが発生しました。アドバイスや助けをいただければ幸いです。前もって感謝します。

4

1 に答える 1

4

理想的には、3つのデータフィールドを1つのベクトルにマージして、struct単純に並べ替えることができます。

struct DataElement{
    std::string str;
    char theChar;
    int num;
    bool operator<(const DataElement& other)const{return theChar<other.theChar;}
};

std::vector<DataElement> myvector;

std::sort (myvector.begin(), myvector.end());
于 2013-02-04T04:44:17.277 に答える