我有一个关于将对象移动到向量对中的前面的问题。我已经读过 that one post 但我不知道如何将它与向量对一起使用,或者更好地说明如何使用字符串来做。我不知道如何用迭代器指向我需要的位置,因为在我的代码中,我还需要一个计数来比较两个字符串,或者如何比较 if(it==ite){..} (我的示例需要 2 个循环,因此我将另一个循环命名为“ite”作为示例。
我有一个 vector
我不知道如何使用向量对来做到这一点。
这是我的代码来理解我的意思:
for(size_t i=0;i<Text.size();i++){
for(size_t j=0;j<Duden.size();j++){
if(Text[i]==Duden[j].first){
uebersetzung.push_back(Duden[j].first);
if(Duden[j].first.length()<4){
uebersetzung.push_back(" ");}
if(Duden[j].first.length()<8){
uebersetzung.push_back("\t");} // These are only so it looks cleaner at the end
uebersetzung.push_back("\t\t\t\t: ");
uebersetzung.push_back(Duden[j].second);
uebersetzung.push_back("\n");
// Now here should be the code to rotate the vector so the found element is now at the first position and not at the found position
break;
}
}
}
如果你想知道的话,这里的“Duden”是字典。我想交换字典中元素的位置,所以如果这个词再次出现在文本中,它不需要再次遍历整个字典,而是直接在第一个位置找到它。
如何使用旋转来实现这一点?或者我是否需要使用擦除和插入来完成,因为旋转不适用于成对的向量?
答案 0 :(得分:1)
考虑使用 STL 库中的算法。要使用它们,您必须熟悉迭代器。然后你可以使用像 std::rotate
这样的东西,你的向量中的内容并不重要。
例如,您的代码可以通过以下方式重构:
for (auto const& word : Text) {
auto it = std::find(Duden.begin(), Duden.end(), [&word](auto const& entry) {
return entry.first == word;
});
if(it == Duden.end()) {
continue;
}
generate_translation(uebersetzung, *it);
std::rotate(Duden.begin(), it, it+1);
}
函数 generate_translation(std::vector<string>&, std::pair<string, string> const&)
应该是一个自己的函数,以使代码更具可读性。
类似的东西
void generate_translation(std::vector<string>& uebersetzung,
std::pair<string, string> const& entry)
{
uebersetzung.push_back(entry.first);
if(entry.first.length() < 4){
uebersetzung.push_back(" ");
}
if(entry.first.length() < 8){
uebersetzung.push_back("\t");
} // These are only so it looks cleaner at the end
uebersetzung.push_back("\t\t\t\t: ");
uebersetzung.push_back(entry.second);
uebersetzung.push_back("\n");
}