0

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?
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
lifebalance
  • 1,846
  • 3
  • 25
  • 57

2 Answers2

5

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...

1

The simplest way of doing this is

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> arr = {11, 22, 33, 44};
    int first = arr[0];
    vector<int> rest;

    for (int i = 1; i < arr.size(); i++) {
        rest.push_back(arr[i]);
    }

    return 0;
}

Or you can do this in this way also,

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> arr = {11, 22, 33, 44};
    int first = arr[0];
    vector<int> rest(arr.begin() + 1, arr.end());

    return 0;
}
AvmnuSng
  • 335
  • 1
  • 2
  • 9