-2

Still a beginner to coding, but is there a way to obtain sub-array from an array without the use of nested loops i.e. more traditional methods?

4
  • 6
    Being a beginner is fine. Asking a coding question without including a sample of the problem you're trying to solve is not. It's like visiting the mechanic about a car problem but forgetting to bring your car. Please edit your question to include any relevant code, ideally in the most minimal form that conveys the specific problem. Commented Mar 2, 2017 at 8:37
  • 2
    I'm also confused by what you mean by "more traditional methods" - IMO loops are one of the most traditional things in programming. Commented Mar 2, 2017 at 8:38
  • 2
    When you say "array" do you mean an old C-style array? When you say "sub-array" what do you mean by that? Why not simply have a pair of indexes (beginning and end)? Or a pair of iterators? Commented Mar 2, 2017 at 8:39
  • You should use iterators, check out this stackoverflow.com/questions/13576160/… Commented Mar 2, 2017 at 8:41

1 Answer 1

1

Assuming you want a copy of a part of a vector, you can use a constructor that takes an interator for the beginning and the end of the new vector.

vector<int> array = {0, 1, 2, 3, 4, 5};
vector<int> subArray(array.cbegin() + 2, array.cbegin() + 4);

for (int i : subArray) {
    cout << i << endl;
}

output:

2
3
Sign up to request clarification or add additional context in comments.

2 Comments

OP never mentioned vectors
The question is too vague to know. Vectors are one of the more classic C++ ways to handle arrays. If the question is updated and it turns out that OP means bare C arrays, std::array, or a pointer I will duly delete my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.