排序向量忽略某个数字

时间:2018-05-21 11:04:21

标签: c++ sorting stl stdvector

我试图对数字向量进行排序并忽略某个数字,即将其保留在原位。 This answer实际上并没有将元素留在原来的位置。

例如,如果我有以下

std::vector<int> test{5, 3, 8, 4, -1, 1, 11, 9, 6};
std::sort(test.begin(), 
         std::partition(test.begin(), test.end(), [](int n)
                                                  {return n != -1;}));

test排序到1 3 4 5 6 8 9 11 -1。我搜索了几个小时,并使用自定义比较器并使用std::partition进行修补,但我无法提出将test向量分类为1 3 4 5 -1 6 8 9 11的解决方案。 这实际上非常困难吗?

4 个答案:

答案 0 :(得分:2)

根据@Bathsheba在他的回答中提到的补救,并且愚弄std::sort()的谓词,可以实现如下解决方案:

DEMO

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> test{5, 3, 8, 4, -1, 1, 11, 9, 6};
    // get the position of -1
    auto itr = std::find(test.begin(), test.end(), -1);
    // sort all elements so that -1 will be moved to end of vector
    std::sort(test.begin(), test.end(), [](const int& lhs, const int& rhs )
        {
            if( lhs == -1 ) return false;
            if( rhs == -1 ) return true;
            return lhs < rhs;
        });

    test.erase(test.end()-1);   //  now erase it from end
    test.insert(itr, -1);       //  insert to the earlier position

    for(const auto& it: test)   std::cout << it << " ";

    return 0;
}

答案 1 :(得分:1)

是的,使用std::sort做这件事很棘手:你不得不欺骗你的比较器将不变数字插入到正确的位置,而且如果事先没有检查其他元素就很难。

一个简单的补救措施是使用插入排序;在你到达时省略不合适的号码(但记录位置),并在该记录位置的末尾手动插入。

答案 2 :(得分:1)

给出一个向量。

  • 找到您要离开的元素的位置。
  • 将其交换到最后。
  • Partial sort向量(没有最后一个元素) - 所选位置之前的所有元素都将被排序,之后会有一个随机顺序。
  • 将元素交换回找到的位置
  • 对矢量的其余部分进行排序

代码:

WebElement element = driver.findElement(by);
element.click();
driver.switchTo().defaultContent(); // or driver.switchTo().parentFrame();
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("xyz")));
// wait for stalenessOf previous element (visibility of next desired element preferred)
new WebDriverWait(driver, 4, 100).until(ExpectedConditions.stalenessOf(element));
// or wait for visibility of next desired element (preferred approach)
new WebDriverWait(driver, 4, 100).until(ExpectedConditions.visibilityOfElementLocated(next_desired_element));

答案 3 :(得分:0)

不将元素交换到最后:

  • 找到元素的位置。
  • 使用比较器对向量进行部分排序,直到排除此位置,使得此元素大于向量的其他元素,以便元素不会出现在部分排序的部分中。
  • 将矢量的其余部分从此位置排序到末尾,使用比较器使该元素小于矢量其余部分的其他元素,这将在此位置重新输入此元素。

代码:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

constexpr int ignored_number = 100;

int main()
{
    vector<int> test{5, 3, 8, 4, ignored_number, 1, 11, 9, 6};

    auto it = find(test.begin(), test.end(), ignored_number);
    partial_sort(test.begin(), it, test.end(), [](int lhs, int rhs) {
        return lhs == ignored_number ? false :
            (rhs == ignored_number ? true : lhs < rhs);
    });
    sort(it, test.end(), [](int lhs, int rhs) {
        return rhs == ignored_number ? false :
            (lhs == ignored_number ? true : lhs < rhs);
    });

    for (const auto& x: test) {
      cout << x << ' ';
    }
    cout << endl;
}
相关问题