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?
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
.
Its working thanks:) and how can i use begin and end for
string langs*
std::partition(langs, langs+n, ...
wheren
is the number of elements. See this Q&A