2

I have an array something like this

int A[] = {1, 2, 3, 4, 5, 6, 7}
vector<int> vec;
int index = 0;
for(int i = 0; i < A.size(); i++) {
if(some condition) {
    index = i;
}
**vec(A + index, i);**
}

how to convert an array to vector starting from particular index, like above ?

1
  • 2
    Why can't you just use vec.push_back() and fill up vector that way? If you want to copy entire array int vector: for(int i = 0; i < 7; i++) vec.push_back(A[i]); Commented Nov 29, 2016 at 13:31

3 Answers 3

5

You can use the index as follows.

#include <iterator>

int A[] = {1, 2, 3, 4, 5, 6, 7};

int index = 0;
for(int i = 0; i < A.size(); i++) {
if( /* some condition */ ) {
    index = i;
    break;
}

}
std::vector<int> vec ( std::begin(A) + index, std::end(A) ) ;
Sign up to request clarification or add additional context in comments.

2 Comments

Showoff ;-). Don't forget to #include the header for std::begin.
@Bathsheba Not really needed. It is guaranteed to be included with vector and the OP should already be including that since they are using a vector.
1

std::vector<int> vec(A + index, A + sizeof(A) / sizeof(A[0])); is the way the cool cats do it.

Comments

-2

As I have seen in the internet you can add elements to the vectors using insert method, you can get all the elements of your array and adding them to the vector with the for loop just like the following code:

int A[] = {1, 2, 3, 4, 5, 6, 7}
vector<int> vec;
int index = 0;
for(int i = 0; i < A.size(); i++) {
if(some condition) {
    vec.insert(vec.begin()+index,A[i]));
    index++;
}
**vec(A + index, i);**
}

See this post for more information

insert an element into a specific position of a vector

4 Comments

insert is for inserting an element at a certain position. when starting with an empty vector using push_back makes more sense
What's A.size()? Missing semi-colon on the first line, wrong no. of brackets at vec.insert() <- which should as pointed out should really just be emplace_back() or push_back() or at the very least construct the vector with a size , and what is **vec(A + index, i);**?
@George I just reused the code of the author so he can see what differences I made on his code. The vec(A + index, i); should be a comment.
@BrankVictoria The main reason I dv'd was that the answer you gave is incorrect even if the op's code were correct. Plus giving back broken code is not a good way to answer a question. If you edit the answer, i'll take my dv off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.