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?
-
6Being 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.tadman– tadman2017-03-02 08:37:10 +00:00Commented Mar 2, 2017 at 8:37
-
2I'm also confused by what you mean by "more traditional methods" - IMO loops are one of the most traditional things in programming.UnholySheep– UnholySheep2017-03-02 08:38:56 +00:00Commented Mar 2, 2017 at 8:38
-
2When 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?Some programmer dude– Some programmer dude2017-03-02 08:39:14 +00:00Commented Mar 2, 2017 at 8:39
-
You should use iterators, check out this stackoverflow.com/questions/13576160/…ibrahimb– ibrahimb2017-03-02 08:41:41 +00:00Commented Mar 2, 2017 at 8:41
Add a comment
|
1 Answer
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
2 Comments
UnholySheep
OP never mentioned vectors
Jozef Legény
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.