Search code examples
c++code-translation

What is the C++ equivalent code of this Python slicing statement?


I am trying to translate the following Python statements to C++:

some_array = [11, 22, 33, 44]
first, rest = some_array[0], some_array[1:]

What I have so far is this:

int array[4] = {11, 22, 33, 44};
vector<int> some_array (array, 4);
int first = some_array.front();
vector<int> rest = some_array;
rest.erase(rest.begin());
  • How can this be shorter and/or efficiently rewritten?
  • Can this be written without using C++ templates and/or vectors?
  • Is there an online service (or software) for translating such non-trivial Python code snippets to human readable C++ code?

Solution

  • This:

    vector<int> rest = some_array;
    rest.erase(rest.begin());
    

    can be shortened to:

    vector<int> rest(some_array.begin() + 1, some_array.end());
    

    If you can use C++11, you can shorten the whole code to:

    vector<int> some_array { 11, 22, 33, 44 };
    int first = some_array.front();
    vector<int> rest (some_array.begin() + 1, some_array.end());
    

    Although I doubt this would be much of an advantage...