如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
how can i sort a 2d vector without change the original vector with insertion sort
嗨,我是 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
我相信这就是您想要的 - 分离的内部向量的排序数据的视图。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 如何在不复制数据的情况下将 cv::Mat 转换为 2d 标准::矢量
- 如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
- 在不使用递归的情况下求解所有 2D 字符串向量组合?(C++)
- 如何在不知道尺寸的情况下在 2D 数组中输入
- 如何在不使用指针的情况下将动态2D数组传递到函数
- 在不知道大小的情况下通过2d阵列
- 如何在不进行内存操作的情况下在 C++ 和 STL 中定义 2D 数组
- 如何在不使用指针的情况下初始化具有可变大小的 2D 数组
- 在没有2D阵列的情况下从矩阵文件中读取坐标
- 我不能在不使用指针的情况下返回 2d 数组!我正在制作一个井字游戏类型游戏,这是我的向上移动功能
- 如何在没有STL的情况下从2d阵列中删除任何未填充的插槽
- 如何在不声明其大小的情况下声明 2D 数组C++
- 如何在这种情况下使用2D矢量
- 如何在不移动整个场景的情况下移动一个2d对象?