Best way to extract a subvector from a vector? - c++

Suppose I have a std::vector (let's call it myVec) of size N. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For example, myVec [100000] through myVec [100999] in a vector of size 150000.
If this cannot be done efficiently with a vector, is there another STL datatype that I should use instead?

vector<T>::const_iterator first = myVec.begin() + 100000;
vector<T>::const_iterator last = myVec.begin() + 101000;
vector<T> newVec(first, last);
It's an O(N) operation to construct the new vector, but there isn't really a better way.

Just use the vector constructor.
std::vector<int> data();
// Load Z elements into data so that Z > Y > X
std::vector<int> sub(&data[100000],&data[101000]);

This discussion is pretty old, but the simplest one isn't mentioned yet, with list-initialization:
vector<int> subvector = {big_vector.begin() + 3, big_vector.end() - 2};
It requires c++11 or above.
Example usage:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> big_vector = {5,12,4,6,7,8,9,9,31,1,1,5,76,78,8};
vector<int> subvector = {big_vector.begin() + 3, big_vector.end() - 2};
cout << "Big vector: ";
for_each(big_vector.begin(), big_vector.end(),[](int number){cout << number << ";";});
cout << endl << "Subvector: ";
for_each(subvector.begin(), subvector.end(),[](int number){cout << number << ";";});
cout << endl;
}
Result:
Big vector: 5;12;4;6;7;8;9;9;31;1;1;5;76;78;8;
Subvector: 6;7;8;9;9;31;1;1;5;76;

std::vector<T>(input_iterator, input_iterator), in your case foo = std::vector<T>(myVec.begin () + 100000, myVec.begin () + 150000);, see for example here

These days, we use spans! So you would write:
#include <gsl/span>
...
auto start_pos = 100000;
auto length = 1000;
auto span_of_myvec = gsl::make_span(myvec);
auto my_subspan = span_of_myvec.subspan(start_pos, length);
to get a span of 1000 elements of the same type as myvec's. Or a more terse form:
auto my_subspan = gsl::make_span(myvec).subspan(1000000, 1000);
(but I don't like this as much, since the meaning of each numeric argument is not entirely clear; and it gets worse if the length and start_pos are of the same order of magnitude.)
Anyway, remember that this is not a copy, it's just a view of the data in the vector, so be careful. If you want an actual copy, you could do:
std::vector<T> new_vec(my_subspan.cbegin(), my_subspan.cend());
Notes:
gsl stands for Guidelines Support Library. For more information about gsl, see: http://www.modernescpp.com/index.php/c-core-guideline-the-guidelines-support-library.
There are several gsl implementations . For example: https://github.com/martinmoene/gsl-lite
C++20 provides an implementation of span. You would use std::span and #include <span> rather than #include <gsl/span>.
For more information about spans, see: What is a "span" and when should I use one?
std::vector has a gazillion constructors, it's super-easy to fall into one you didn't intend to use, so be careful.

If both are not going to be modified (no adding/deleting items - modifying existing ones is fine as long as you pay heed to threading issues), you can simply pass around data.begin() + 100000 and data.begin() + 101000, and pretend that they are the begin() and end() of a smaller vector.
Or, since vector storage is guaranteed to be contiguous, you can simply pass around a 1000 item array:
T *arrayOfT = &data[0] + 100000;
size_t arrayOfTLength = 1000;
Both these techniques take constant time, but require that the length of data doesn't increase, triggering a reallocation.

You didn't mention what type std::vector<...> myVec is, but if it's a simple type or struct/class that doesn't include pointers, and you want the best efficiency, then you can do a direct memory copy (which I think will be faster than the other answers provided). Here is a general example for std::vector<type> myVec where type in this case is int:
typedef int type; //choose your custom type/struct/class
int iFirst = 100000; //first index to copy
int iLast = 101000; //last index + 1
int iLen = iLast - iFirst;
std::vector<type> newVec;
newVec.resize(iLen); //pre-allocate the space needed to write the data directly
memcpy(&newVec[0], &myVec[iFirst], iLen*sizeof(type)); //write directly to destination buffer from source buffer

You could just use insert
vector<type> myVec { n_elements };
vector<type> newVec;
newVec.insert(newVec.begin(), myVec.begin() + X, myVec.begin() + Y);

You can use STL copy with O(M) performance when M is the size of the subvector.

Suppose there are two vectors.
vector<int> vect1{1, 2, 3, 4};
vector<int> vect2;
Method 1. Using copy function. copy(first_iterator_index, last_iterator_index, back_inserter()) :- This function takes 3 arguments, firstly, the first iterator of old vector. Secondly, the last iterator of old vector and third is back_inserter function to insert values from back.
// Copying vector by copy function
copy(vect1.begin(), vect1.end(), back_inserter(vect2));
Method 2. By using Assign Function. assign(first_iterator_o, last_iterator_o). This method assigns the same values to new vector as old one. This takes 2 arguments, first iterator to old vector and last iterator to old vector.
//Copying vector by assign function
vect2.assign(vect1.begin(), vect1.end());

The only way to project a collection that is not linear time is to do so lazily, where the resulting "vector" is actually a subtype which delegates to the original collection. For example, Scala's List#subseq method create a sub-sequence in constant time. However, this only works if the collection is immutable and if the underlying language sports garbage collection.

Maybe the array_view/span in the GSL library is a good option.
Here is also a single file implementation: array_view.

Copy elements from one vector to another easily
In this example, I am using a vector of pairs to make it easy to understand
`
vector<pair<int, int> > v(n);
//we want half of elements in vector a and another half in vector b
vector<pair<lli, lli> > a(v.begin(),v.begin()+n/2);
vector<pair<lli, lli> > b(v.begin()+n/2, v.end());
//if v = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
//then a = [(1, 2), (2, 3)]
//and b = [(3, 4), (4, 5), (5, 6)]
//if v = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
//then a = [(1, 2), (2, 3), (3, 4)]
//and b = [(4, 5), (5, 6), (6, 7)]
'
As you can see you can easily copy elements from one vector to another, if you want to copy elements from index 10 to 16 for example then we would use
vector<pair<int, int> > a(v.begin()+10, v.begin+16);
and if you want elements from index 10 to some index from end, then in that case
vector<pair<int, int> > a(v.begin()+10, v.end()-5);
hope this helps, just remember in the last case v.end()-5 > v.begin()+10

Yet another option:
Useful for instance when moving between a thrust::device_vector and a thrust::host_vector, where you cannot use the constructor.
std::vector<T> newVector;
newVector.reserve(1000);
std::copy_n(&vec[100000], 1000, std::back_inserter(newVector));
Should also be complexity O(N)
You could combine this with top anwer code
vector<T>::const_iterator first = myVec.begin() + 100000;
vector<T>::const_iterator last = myVec.begin() + 101000;
std::copy(first, last, std::back_inserter(newVector));

vector::assign may be another solution
// note: size1 < src.size() && size2 < src.size()
std::vector<int> sub1(size1), sub2(size2);
sub1.assign(src.begin(), src.begin() + size1);
sub2.assign(src.begin(), src.begin() + size2);

Posting this late just for others..I bet the first coder is done by now.
For simple datatypes no copy is needed, just revert to good old C code methods.
std::vector <int> myVec;
int *p;
// Add some data here and set start, then
p=myVec.data()+start;
Then pass the pointer p and a len to anything needing a subvector.
notelen must be!! len < myVec.size()-start

Related

Problems using 3-dimensional vector

How can I work with a 3 dimensional vector in C++?
vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));
When I try something like this
cout << vec[0][0][0]; vec[0][0][1] = 13;
everything works just fine.
The problem is that I can only change the last elements. If I try accessing the first and second element, like this
vec[0][1][0] = 13;
or this
vec.push_back(vector<vector<int > >());
vec[0].push_back(vector<int>());
v[1][0].push_back(13);
my program crashes.
How can I add and access elements in a 3d vector?
I would never do vector<vector<vector<int> > > as in this way you have many allocations what could be expensive. I would simply use vector<int> with smart indexing (e.g.: see below). If you will work with double based matrices, in this way intel MKL or any other BLAS library easily could be used.
Its price is increased complexity when matrix sizes are changed, but you could win many in performance.
Useful link: C++ FAQ.
static int const M = 16;
static int const N = 16;
static int const P = 16;
inline int& set_elem(vector<int>& m_, size_t i_, size_t j_, size_t k_)
{
// you could check indexes here e.g.: assert in debug mode
return m_[i_*N*P + j_*P + k_];
}
inline const int& get_elem(const vector<int>& m_, size_t i_, size_t j_, size_t k_)
{
// you could check indexes here e.g.: assert in debug mode
return m_[i_*N*P + j_*P + k_];
}
vector<int> matrix(M*N*P, 0);
set_elem(matrix, 0, 0, 1) = 5;
vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));
cout << vec[0][0][0]; vec[0][0][1] = 13;
evething is OK.
You are mistaken. Everything is not OK. The vector vec[0][0] has only one element and thus vec[0][0][1] is out of bounds and therefore the assignment has undefined behaviour. You have the same problem with vec[0][1][0] = 13; and v[1][0].push_back(13)
You can fix that by accessing only indices that exist in your vectors. If you want more than one element, then either construct the vectors with more elements initially, or push them after construction.
At the begining I have 1x1x1 vector. So how can I push elements. using push_back() ? For example I have 1x1x1 and I want to add v[1][1][0] = 2 ?
If you for some reason want to start with 1x1x1 vector of vectors of vectors of ints and want to access v[1][1][0], here is example code to add the v[1][1][0] element with minimal changes to the original vector:
// vector of ints that contains one element, 2
// this will vector eventually be the v[1][1] and the integer element will be v[1][1][0]
// since we initialize the integer as 2, there's no need to assign it later though
vector<int> vi(1, 2);
// vector of vectors that contains one default constructed vector
// vvi will eventually be the v[1] element and the default constructed vector will be v[1][0]
vector<vector<int>> vvi(1);
// push vi into vvi, making it vvi[1] and eventually v[1][1]
vvi.push_back(vi);
// push vvi into v, making it v[1]
v.push_back(vvi);
What you have,
vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));
creates 1 x 1 x 1 matrix with the value of the only element set to 12.
To create something that is analogous to a M x N x P matrix, you need to use:
vector<vector<vector<int> > > vec (M,vector<vector<int> >(N,vector <int>(P,x)));
That will create an M x N x P matrix with the value of each element set to x.

C++ multidimensional arrays

i was thinkg about writing a code that creates a pascal triangle. I 've done it but then i thought about doing it better. One idea came to my mind but i couldnt find a proper answer for it. Is it possible to create an array which will be look like that?
[1]|[1][1]|[1][2][1]|[1][3][3][1]|[1][4][6][4][1]| and so on? so my [1] would be (0,0) and [1][2][1] would be elements of cells(2,0),(2,1),(2,2). I would be grateful for any advise.
You can implement triangle array through a single-dimension array. Fixed-size array may look like this:
template<typename T, size_t N>
struct TriangleArray {
T& element(size_t i, size_t j)
{
if (i >= N || j >= N || i < j)
throw std::out_of_range("incorrect index");
return container[(i + 1) * i / 2 + j];
}
private:
T container[(N + 1) * N / 2];
};
No it's not possible. In an array, all the element must have the same type. Two dimensional arrays are arrays of arrays. That means that for a multidimensional array, all the line must have the same length. You should probably use a
std::vector<std::vector<int> >
here. Or a one dimensional array and and the logic to compute the 1 dim position from the 2 dim index:
index = row*(row+1)/2 + column.
See iterate matrix without nested loop if you want the reverse indexing.
Edit: fixed my formula which was off by one. Here is a check in Python:
The following index function takes row, col and compute the corresponding index in a one dimensional array using my formula:
>>> index = lambda row, col: row*(row+1)/2 + col
Here are the coordinate pairs
>>> [[(i,j) for j in range(i+1)] for i in range(5)]
[[(0, 0)],
[(1, 0), (1, 1)],
[(2, 0), (2, 1), (2, 2)],
[(3, 0), (3, 1), (3, 2), (3, 3)],
[(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]]
I'm now checking that the corresponding index are the sequence of integer starting from 0 (indentation of the printing is mine):
>>> [[index(i,j) for j in range(i+1)] for i in range(5)]
[[0],
[1, 2],
[3, 4, 5],
[6, 7, 8, 9],
[10, 11, 12, 13, 14]]
The nicest thing would be to wrap the whole thing in a class called PascalTriangle and implement it along the following lines:
class PascalTriangle
{
private:
std::vector<std::vector<int> > m_data;
std::vector<int> CalculateRow(int row_index) const
{
// left as an exercise :)
}
public:
PascalTriangle(int num_rows) :
m_data()
{
assert(num_rows >= 0);
for (int row_index = 0; row_index < num_rows; ++row_index)
{
m_data.push_back(CalculateRow(row_index));
}
}
int operator()(int row_index, int column_index) const
{
assert(row_index >= 0 && row_index < m_data.size());
assert(column_index >= 0 && column_index < row_index);
return m_data[row_index][column_index];
}
};
Now here comes the catch: this approach allows you to perform lazy evaluation. Consider the following case: you might not always need each and every value. For example, you may only be interested in the 5th row. Then why store the other, unused values?
Based on this idea, here's an advanced version of the previous class:
class PascalTriangle
{
private:
int m_num_rows;
std::vector<int> CalculateRow(int row_index) const
{
// left as an exercise :)
}
public:
PascalTriangle(int num_rows) :
m_num_rows(num_rows)
{
assert(num_rows >= 0);
// nothing is done here!
}
int operator()(int row_index, int column_index) const
{
assert(row_index >= 0 && row_index < m_num_rows);
assert(column_index >= 0 && column_index < row_index);
return CalculateRow(row_index)[column_index];
}
};
Notice that the public interface of the class remains exactly the same, yet its internals are completely different. Such are the advantages of proper encapsulation. You effectively centralise error handling and optimisation points.
I hope these ideas inspire you to think more about the operations you want to perform with your Pascal triangle, because they will dictate the most appropriate data structure.
Edit: by request, here are some more explanations:
In the first version, m_data is a vector of vectors. Each contained std::vector<int> represents a row in the triangle.
The operator() function is a syntactical helper, allowing you to access PascalTriangle objects like this:
PascalTriangle my_triangle(10);
int i = my_triangle(3, 2);
assert makes sure that your code does not operate on illegal values, e.g. a negative row count or a row index greater than the triangle. But this is just one possible error reporting mechanism. You could also use exceptions, or error return values, or the Fallible idiom (std::optional). See past Stackoverflow questions for which error reporting mechanism to use when. This is a pure software-engineering aspect and has nothing to do with maths, but as you can imagine, it's, well, very important in software :)
CalculateRow returns a std::vector<int> representing the row specified by row_index. To implement it correctly, you'll need some maths. This is what I just found on Google: http://www.mathsisfun.com/pascals-triangle.html
In order to apply the maths, you'll want to know how to calculate n! in C++. There have been a lot of past Stackoverflow questions on this, for example here: Calculating large factorials in C++
Note that with the class approach, you can easily switch to another implementation later on. (You can even take it to the extreme and switch to a specific calculation algorithm based on the triangle height, without the users of the class ever noticing anything! See how powerful proper encapsulation can be?)
In the second version of the class, there is no permanent data storage anymore. CalculateRow is called only if and when needed, but the client of the class doesn't know this. As an additional possibly performance-improving measure, you could remember rows which you already calculated, for example by adding a private std::map<int, std::vector<int> > member variable whose int key represents the row index and whose values the rows. Every CalculateRow call would then first look if the result is already there, and add calculated ones at the end:
private mutable std::map<int, std::vector<int> > m_cache;
std::vector<int> CalculateRow(int row_index) const
{
// find the element at row_index:
std::map<int, std::vector<int> >::const_iterator cache_iter =
m_cache.find(row_index);
// is it there?
if (cache_iter != m_cache.end())
{
// return its value, no need to calculate it again:
return cache_iter->second;
}
// actual calculation of result left as an exercise :)
m_cache[row_index] = result;
return result;
}
By the way, this would also be a nice application of the new C++11 auto keyword. For example, you'd then just write auto cache_iter = m_cache.find(row_index);
And here's for another edit: I made m_cache mutable, because otherwise the thing wouldn't compile, as CalculateRow is a const member function (i.e. shouldn't change an object of the class from the client's point of view). This is a typical idiom for cache member variables.

Convert two vectors of int with the same length into one vector of pairs of int in C++

In C++, if I have two vectors of int:
A = [1, 2, 3 ,4];
B = [1, 2, 3, 4];
How can I merge them into one vector of pairs:
[(1,1), (2,2), (3,3), (4, 4)]
Of course I can do that with a loop. But can we do that using suitable STL functions and iterators?
You can use an algorithm for this:
std::vector<std::pair<int, int>> target;
target.reserve(A.size());
std::transform(A.begin(), A.end(), B.begin(), std::back_inserter(target),
[](int a, int b) { return std::make_pair(a, b); });
I agree that Dietmar Kühl's answer does exactly what was asked in the question, but I also agree with Kakadur's comment. A loop is hidden in std::transform() so the complexity is the same. Some people will judge, but if there is no direct proof of one way being better than the other, I tend to choose the most readable and least verbose version:
// create a vector of length of the smaller vector
std::vector<std::pair<int, int>> target( A.size() < B.size() ? A.size() : B.size() );
for (unsigned i = 0; i < target.size(); i++)
target[i] = std::make_pair(A[i], B[i]);
P.S.
The code above allocates just enough space for the target vector, so that the potential overhead of push_back (in case of reallocation) can be avoided.

How to obtain the index of the median using STL?

How to calculate the median of a digital number array has been discussed before. For example, you can refer to What is the right approach when using STL container for median calculation?. Now I have a different question, and that is how can you get the index of the median in the original STL container. In order to illustrate my question, I give an example:
vector<int> myarray;
myarray.push_back(3);
myarray.push_back(1);
myarray.push_back(100);
myarray.push_back( 20);
myarray.push_back(200);
int n = myarray.size()/2;
nth_element(myarray.begin(), myarray.begin()+n, myarray.end());
int median = myarray[n];
In the above codes I can get the median value but I can not get its index in the original vector array (4). Any ideas? Thanks!
I think there is no straight-forward way to do that.
The vector that you sorted has changed its order, so that searching in that will always return n.
You need to save a copy of your original vector, and search in that. Keep in mind that if the original vector contained duplicates, you will not know exactly which of them was actually put to position n (if this is of any relevance for you).
As an alternative, you could have a look at the implementation of nth_element, and implement your own version that also reports the original position of the found n-th element.
If it is accapteble to search the element
vector<int>::iterator itOfMedian = std::find(myarray.begin(), myarray.end(), median);
int index = itOfMedian - myarray.begin();
should do the trick.
EDIT
seems you have point here. nth_element sorts its argument vector... Therefore
vector<int> myArrayCopy = myarray;
// find median in myArrayCopy
vector<int>::iterator itOfMedian = std::find(myarray.begin(), myarray.end(), median);
int index = itOfMedian - myarray.begin();
You can use std::nth_element to find an iterator to the median element. However, this does a partial sorting of the vector, so you would need to use a copy:
std::vector<int> dataCopy = myarray;
// we will use iterator middle later
std::vector<int>::iterator middle = dataCopy.begin() + (dataCopy.size() / 2);
// this sets iterator middle to the median element
std::nth_element(dataCopy.begin(), middle, dataCopy.end());
int nthValue = *middle;
Now it gets complicated. You have a value corresponding to the median. You can search the original vector for it, and use std::distance to get the index:
std::vector<int>::iterator it = std::find(myarray.begin(), myarray.end(), nthValue);
std::vector<int>::size_type pos = std::distance(myarray.begin(), it);
however, this only works if there are not duplicates of nthValue in myarray.
Sorry to dig up an old topic, but here's a nice way to do it. Exploit the fact that nth_element will sort a pair by the first element; with this in mind, create a vector of pairs where the first part of the pair is value to participate in median calculation, and second is index. Modifying your example:
vector<pair<unsigned int, size_t>> myarray;
myarray.push_back(pair<unsigned int, size_t>( 3, 0));
myarray.push_back(pair<unsigned int, size_t>( 1, 1));
myarray.push_back(pair<unsigned int, size_t>(100, 2));
myarray.push_back(pair<unsigned int, size_t>( 20, 3));
myarray.push_back(pair<unsigned int, size_t>(200, 4));
int n = myarray.size()/2;
nth_element(myarray.begin(), myarray.begin()+n, myarray.end());
int median = myarray[n].first;
int medianindex = myarray[n].second;
Of course myarray has been rearranged, and so myarray[medianindex] is not the median. If you made a copy before nth_element, medianindex would be the desired index.

Fixed length structure re-arrange: should I use array or linked list?

This structure will only contain exactly 256 unsigned chars.
The only operation possible is taking random characters from it and putting them in front of the structure.
For example:
A= 'abcdef'
Move character 2 to front
A= 'cabdef'
I first thought of using linked link so that it could work as a queue.
Thing is I heard that arrays are much faster than linked lists for these operations. Is this true?
A linked list will be O(1) and an array will be O(n) for a move operation as you have described. For small n the array will probably be faster, but the only way to know for sure is to benchmark.
In a case like this I would code what's clearest and only worry about efficiency if it proves to be a bottleneck.
P.S. I made an assumption that you already had a pointer to the character you want to move. If this is not the case, then finding the character will be O(n) in the linked list and you will lose any advantages it might have.
Use an array. The linked list will be huge and unwieldy for storage of char data.
A linked list would be a good approach since you don't need to move all the intermediate elements around. std::list works just fine, combined with splice(). You will need an iterator to the element you want to move to the front:
#include <list>
#include <iostream>
#include "prettyprint.hpp"
int main()
{
std::list<int> x { 1, 4, 6, 7, 2 };
auto i = x.begin(); std::advance(i, 2); // i points to 6
std::cout << x << std::endl; // [1, 4, 6, 7, 2]
x.splice(x.begin(), x, i);
std::cout << x << std::endl; // [6, 1, 4, 7, 2]
}
(Using the pretty printer for a quick demo.)
As others have said, whether that's more efficient that a random-access container depends on how you are tracking the element that you want to move.
Update: In light of Steve's remarks I should like to offer a raw C-array solution, too. It has the benefit that you can access it by position in O(1) time and that it requires minimum space:
char y[] = { 'a', 'c', 'Q', '%', '5' };
std::cout << pretty_print_array(y) << std::endl; // [a, c, Q, %, 5]
std::rotate(y, y + 2, y + sizeof(y));
std::cout << pretty_print_array(y) << std::endl; // [Q, %, 5, a, c]
The rotate call could be wrapped in a function:
template <typename T, size_t N>
void bring_forward(T (& a)[N], size_t p) { std::rotate(a, a + p, a + N); }
In C++, you can use a vector instead of array or linked list. The complexity of a Linked List is O(1) like #Mark Ransom said. With the vector, you can use the command rotate to perform the action you desire. The complexity is determined by the number of swaps.
From MSDN, how to use rotate:
const int VECTOR_SIZE = 8;
// Define a template class vector of strings
typedef vector<string> StrVector;
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt;
StrVector Tongue_Twister(VECTOR_SIZE);
StrVectorIt start, end, middle, it;
// location of first element of Tongue_Twister
start = Tongue_Twister.begin();
// one past the location last element of Tongue_Twister
end = Tongue_Twister.end();
// Initialize vector Tongue_Twister
Tongue_Twister[0] = "she";
Tongue_Twister[1] = "sells";
Tongue_Twister[2] = "sea";
Tongue_Twister[3] = "shells";
Tongue_Twister[4] = "by";
Tongue_Twister[5] = "the";
Tongue_Twister[6] = "sea";
Tongue_Twister[7] = "shore";
middle = start + 3; // start position for rotating elements
cout << "Before calling rotate" << endl;
// print content of Tongue_Twister
cout << "Try this Tongue Twister:";
for (it = start; it != end; it++)
cout << " " << *it;
// rotate the items in the vector Tongue_Twister by 3 positions
rotate(start, middle, end);
Or you can do it with arrays:
// create an array of 9 elements and rotate the entire array.
int myArray[SIZE] = { 7, 8, 9, 1, 2, 3, 4, 5, 6, };
std::rotate(myArray, myArray + 3, myArray + SIZE);
How fast is this? I don't know. I haven't benchmarked it. But it is much easier than having to manually swap elements of an array.
The array will be O(1) to find the item and O(n) to move it and the other items into the correct position. The linked list will be O(n) to find the item and O(1) to move everything to the right position. The complexity is the same either way.
They're both easy to implement, so implement both of them and run tests to see which one lets your program run faster with real-world data.
C++ arrays are linked lists, so moving an element to the front of your list is cheap, provided you already know where the element is (i.e. you have an iterator on it). Using a vector would cause the entire list to be shifted each time an element is pushed in front of it.