c++ - 如何在不使用插入排序更改原始向量的情况下对二维向量进行排序
问题描述
嗨,我是 C++ 和指针的新手,所以我只想问一下如何在不直接排序的情况下插入对 2d 字符串向量 x 进行排序
最后它应该看起来像
vector[vector[sorted],vector[sorted]........]
要求:(不要直接对字符串进行排序,因为这会导致数据移动过多。为了有效,请对指向字符串的指针进行排序。)我唯一可以使用的库是 iostream、vector 和 string
所以我必须创建一个指向二维向量的二维向量指针,然后对指针 pos 进行排序,所以我试图创建一个
vector<vector<string>> *p
指向二维向量,但我找不到除了(*p)[i][j]
访问向量之外的方法,但(*p)[i][j]
会编辑原始向量。
我在不使用指针的情况下实现了它
shiftstring 来自读取文件中的每一行,然后对每一行进行循环移位,
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 矢量的指针。你想要一个指向你的字符串的指针的二维向量,即: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';
}
}
请注意,我正在使用std::sort
from <algorithm>
。在那里你应该实现你的插入排序而不是调用标准算法。由于这是一项作业,因此我不会为您提供该部分。请记住-您正在对指针进行排序,但要根据它们所指向的内容来比较它们。
上面显示的输入代码产生以下输出:
some text
in multiple vectors
to
be sorted
我相信这就是您想要的 - 对分离的内部向量的排序数据的视图。
推荐阅读
- java - 实现DateTimeFormatter Y10K输出等于SimpleDateFormat?
- gtk3 - Vala中的外部'C'结构
- c++ - operator = 在深拷贝机制中的实现
- excel - 我在 C 列中查找特定单词的公式(存在于多个单元格中),在 D 列中取相应的金额,然后将金额相加
- python - PyVisa 提供过时的工具列表
- vhdl - 如何将 vhdl 中的频率设置为 0.01 Hz?
- plugins - Lightning Web 组件的本地开发服务器
- javascript -
- javascript - 我希望每个圆圈在 Javascript 中的不同时间按顺序移动
- python - 数据透视表未显示所有 df 值