Warm tip: This article is reproduced from serverfault.com, please click

How to shift elements to end of the array

发布于 2020-12-13 23:12:38

I have this array:

std::string langs[] = { "C++", "Ada", "Haskell", "Python", "Ada" };

I would like to write a function to shift K elements to the end for instance:

k="Ada";

{ "C++", "Haskell", "Python", "Ada", "Ada" };

I wrote this but its not working:

void moved(T e) 
{ 

    istd::vector<int> indexes;
        for (int i = 0; i < size_array; ++i)
        {
            if (array[i] == e)
            {
                indexes.push_back(i);
            }
        }
        
        for (int j = 0; j < (int)indexes.size(); ++j)
        {
            T temp=e;
            for (int i = indexes[j]; i < deleted_array_size-1; ++i)
            {
                array[i] = array[i + 1];
                std::cout << i << std::endl;
            }
            deleted_array_size--;
            array[deleted_array_size - 1] = temp;
            
        }
} 

How can I shift the elements?

Questioner
Jttaskk
Viewed
0
kmdreko 2020-12-14 07:27:27

If the order doesn't matter you can use std::partition:

int main()
{
    std::string langs[] = { "C++", "Ada", "Haskell", "Python", "Ada" };
    std::partition(std::begin(langs), std::end(langs), [](auto& lang) {
        return lang != "Ada";
    });
 
    for (auto& str : langs) {
        std::cout << str << std::endl;
    }
}

prints:

C++
Python
Haskell
Ada
Ada

If ordering does matter you can use std::stable_partition.