murthi
murthi

Reputation: 175

Converting an array of int, to a vector of int in c++

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 ?

Upvotes: 2

Views: 1393

Answers (3)

P0W
P0W

Reputation: 47784

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) ) ;

Upvotes: 5

Brank Victoria
Brank Victoria

Reputation: 1455

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

Upvotes: -2

Bathsheba
Bathsheba

Reputation: 234635

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

Upvotes: 1

Related Questions