如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序

how can i sort a 2d vector without change the original vector with insertion sort

本文关键字:情况下 2D 排序 原始 插入排序      更新时间:2023-10-16

嗨,我是 C++ 和指针的新手,所以我只想问 如何在不直接排序的情况下插入对 2D 字符串向量 X 进行排序

最后它应该看起来像
vector[vector[sorted],vector[sorted]........]

要求:(不要直接对字符串进行排序,因为这会导致过多的数据移动。为了提高效率,请改为对指向字符串的指针进行排序。 ( 我唯一可以使用的库是 iostream、向量和字符串

所以我必须创建一个指向 2D 矢量的 2D 矢量指针,然后对指针 POS 进行排序 所以我试图创建一个

vector<vector<string>> *p   

指向 2d 矢量,但我找不到除了(*p)[i][j]之外的访问矢量的方法 但(*p)[i][j]将编辑原始矢量。

我已经在不使用指针的情况下实现了它

shiftstring 来自读取文件中的每一行,然后对每一行执行 cirual shift,

vector<vector<string > > shiftstring;
for (int y = 0; y < shiftstring.size(); y++) 
{
for (int i = 1; i < shiftstring[y].size(); i++) 
{
string key = shiftstring[y][i];
int j = i - 1;
while (j >= 0 && shiftstring[y][j] > key) {
shiftstring[y][j + 1] = shiftstring[y][j];
j = j - 1;
}
shiftstring[y][j + 1] = key;
}
}

看来你只是放错了指针 - 你不想要指向 2D 矢量的指针。你想要一个指向字符串的指针的 2D 向量,即:std::vector<std::vector<const std::string*>>.我提出以下解决方案:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
// the original vector
std::vector<std::vector<std::string>> vec {
{"text", "some"},
{"multiple", "in", "vectors"},
{"to"},
{"sorted", "be"}
};
// the view - vector of vectors of pointers to the strings
std::vector<std::vector<const std::string*>> sorted_view{};
// for each vector of strings inside the vector of vectors...
for (const auto& v : vec) {
// ...we create a vector of views...
sorted_view.emplace_back();
// ...and push_back a pointer to that string into our view-vector
for (const auto& str : v) {
sorted_view.back().push_back(&str);
}
}
// for every view-vector...
for (auto& view : sorted_view) {
// ...sort the pointers of that vector according to what they point to
std::sort(view.begin(), view.end(), [](const auto& lhs, const auto& rhs) {
return *lhs < *rhs;
});
}
// print the view-vector
for (const auto& v : sorted_view) {
for (const auto ptr : v) {
std::cout << *ptr << ' ';
}
std::cout << 'n';
}
}

请注意,我使用的是<algorithm>中的std::sort。在那里,您应该实现插入排序,而不是调用标准算法。由于这是一项作业,我不会为您提供该部分。请记住 - 您正在对指针进行排序,但会根据它们指向的内容进行比较。

上述代码用于所示输入,生成以下输出:

some text
in multiple vectors
to
be sorted

我相信这就是您想要的 - 分离的内部向量的排序数据的视图。