Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producing a subList from a vector<int> in C++

Tags:

c++

stl

is there a built-in STL method to do that?

In java, there is list.subList(a,b) for extracting [a,b). Similar method in STL C++?

like image 482
user855 Avatar asked Aug 28 '11 18:08

user855


People also ask

How do you create a sub vector?

Getting a subvector from a vector in C++auto last = v. begin() + n + 1. Declare a variable vector of vector type. Pass the value of first and last position of vector.

Can a vector have multiple data types?

“No” C++ is a statically-typed language. A vector will hold an object of a single type, and only a single type.

What is vector int A?

the int in vector is specifying its type. like in array when we declare array we specify its members types. int arrr[]; same case with vector(which is a dynamic array) so we have to specify its type to declare it.

How do you shorten a vector in CPP?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.


2 Answers

Sure.

std::vector<int> subList(&originalVector[a], &originalVector[b]);
like image 56
Puppy Avatar answered Sep 17 '22 17:09

Puppy


You can do:

#include <vector>
#include <cassert>

int main() {
    std::vector<int> x;

    for (int i=0; i<10; ++i) {
        x.push_back(i);
    }

    // Here we create a copy of a subsequence/sublist of x:
    std::vector<int> slice_of_x(x.begin() + 3, x.begin() + 7);

    assert(slice_of_x.size() == 7-3);
    assert(slice_of_x[0] == 3);

    return 0;
}

This will make a copy of the requested part of x. If you don't need a copy and would like to be more efficient, it might be preferable to pass around iterator (or pointer) pairs. That would avoid copying.

like image 38
Magnus Hoff Avatar answered Sep 16 '22 17:09

Magnus Hoff