按索引值的字母顺序对向量进行排序

Sorting Vector Alphabetically by Index Value

本文关键字:向量 排序 顺序 索引值      更新时间:2023-10-16

我有一个向量,我想按字母顺序排序。我已经成功地按字母顺序按一个索引值对其进行排序,但是当我这样做时,只会更改该索引的顺序,而不是整个向量。如何让它将阶次更改应用于整个向量?这是我当前正在运行的代码:

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);
}

我这个向量的一般结构是向量[行][列],其中:

| 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 个数据字段合并为一个struct,这样您就可以只有 1 个向量,从而简单地对其进行排序。

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());