更改或删除矢量元素

问题描述 投票:1回答:1

我有以下问题。我的向量包含成对对(参见下面的示例)。在下面的例子中,我将push_back向量与一些“随机”数据。删除向量元素的最佳解决方案是,如果它们的任何值相等,即100,如果小于100,则更新值。

typedef std::pair<int, int> MyMap;
typedef std::pair<MyMap, MyMap> MyPair;

MyMap pair1;
MyMap pair2;

在第一个例子中,我想更新这个对,因为pair1.first小于100

pair1.first = 0;
pair1.second = 101;
pair2.first = 101;
pair2.second = 101;

在第二个例子中,我想删除这一对,因为pair2.first等于100

pair1.first = 0;
pair1.second = 101;
pair2.first = 100;
pair2.second = 101;

使用仿函数“检查”我能够删除一个或多个元素(在这个例子中只有一个)。使用std :: replace_if函数可以将该对的每个值增加1吗?是否有任何函数会更新此值,如果这些值中的任何一个值低于“X”并且如果这些值中的任何一个将等于“X”则删除?我知道如何编写自己的函数,但我很好奇。

#include "stdafx.h"
#include<algorithm>
#include<vector>
#include<iostream>

typedef std::pair<int, int> MyMap;
typedef std::pair<MyMap, MyMap> MyPair;

void PrintAll(std::vector<MyPair> & v);
void FillVectorWithSomeStuff(std::vector<MyPair> & v, int size);

class check
{
public:
    check(int c)
        : cmpValue(c)
    {
    }

    bool operator()(const MyPair & mp) const
    {
        return (mp.first.first == cmpValue);
    }

private:

    int cmpValue;

};

int _tmain(int argc, _TCHAR* argv[])
{
    const int size = 10;
    std::vector<MyPair> vecotorOfMaps;
    FillVectorWithSomeStuff(vecotorOfMaps, size);
    PrintAll(vecotorOfMaps);

    std::vector<MyPair>::iterator it = std::find_if(vecotorOfMaps.begin(), vecotorOfMaps.end(), check(0));
    if (it != vecotorOfMaps.end()) vecotorOfMaps.erase(it);

    PrintAll(vecotorOfMaps);

    system("pause");
    return 0;
}

std::ostream & operator<<(std::ostream & stream, const MyPair & mp)
{
    stream << "First:First = "  << mp.first.first  << " First.Second = "  << mp.first.second  << std::endl;
    stream << "Second:First = " << mp.second.first << " Second.Second = " << mp.second.second << std::endl;
    stream << std::endl;

return stream;
}

void PrintAll(std::vector<MyPair> & v)
{
    for (std::vector<MyPair>::iterator it = v.begin(); it != v.end(); ++it)
    {
        std::cout << *it;
    }
}

void FillVectorWithSomeStuff(std::vector<MyPair> & v, int size)
{
    for (int i = 0; i < size; ++i)
    {
        MyMap m1(i + i * 10, i + i * 20);
        MyMap m2(i + i * 30, i + i * 40);
        MyPair mp(m1, m2);
        v.push_back(mp);
    }
}
c++ vector std-pair
1个回答
0
投票

使用std::stable_partition,以及std::for_each

#include <algorithm>
//...partition the elements in the vector
std::vector<MyPair>::iterator it = 
    std::stable_partition(vecotorOfMaps.begin(), vecotorOfMaps.end(), check(0));

//erase the ones equal to "check"
vecotorOfMaps.erase(vecotorOfMaps.begin(), it);

// adjust the ones that were left over
for_each(vecotorOfMaps.begin(), vecotorOfMaps.end(), add(1));

基本上,stable_partition将您要删除的所有项目放在数组的前面(partiton it的左侧),以及it右侧的所有其他项目。

然后所做的就是擦除it左边的项目(因为它们等于100),一旦完成,就通过生成的向量,向eac添加1

© www.soinside.com 2019 - 2024. All rights reserved.