Creating a new C++ subvector?

后端 未结 4 451
遇见更好的自我
遇见更好的自我 2021-01-07 19:08

Say I have a vector with values [1,2,3,4,5,6,7,8,9,10]. I want to create a new vector that refers to, for example, [5,6,7,8]. I imagine this is just a matter of creating a v

相关标签:
4条回答
  • 2021-01-07 19:50

    You don't have to use push_back if you don't want to, you can use std::copy:

    std::vector<int> subvector;
    copy ( v1.begin() + 4, v1.begin() + 8, std::back_inserter(subvector) );
    
    0 讨论(0)
  • 2021-01-07 19:51

    This is fairly easy to do with std::valarray instead of a vector:

    #include <valarray>
    #include <iostream>
    #include <iterator>
    #include <algorithm>
    
    int main() {
      const std::valarray<int> arr={0,1,2,3,4,5,6,7,8,9,10};
    
      const std::valarray<int>& slice = arr[std::slice(5, // start pos
                                                       4, // size
                                                       1  // stride
                                                      )];
    
    }
    

    Which takes a "slice" of the valarray, more generically than a vector.

    For a vector you can do it with the constructor that takes two iterators though:

    const std::vector<int> arr={0,1,2,3,4,5,6,7,8,9,10};
    std::vector<int> slice(arr.begin()+5, arr.begin()+9);
    
    0 讨论(0)
  • 2021-01-07 19:53

    I would do the following:

    #include <vector>
    #include <iostream>
    
    using namespace std;
    
    void printvec(vector<int>& v){
            for(int i = 0;i < v.size();i++){
                    cout << v[i] << " ";
            }
            cout << endl;
    }
    
    int main(){
            vector<int> v;
    
            for(int i = 1;i <= 10;i++) v.push_back(i);
            printvec(v);
    
            vector<int> v2(v.begin()+4, v.end()-2);
            printvec(v2);
            return 0;
    }
    

    ~

    0 讨论(0)
  • 2021-01-07 19:55

    One of std::vector's constructor accepts a range:

    std::vector<int> v;
    
    // Populate v.
    for (int i = 1; i <= 10; i++) v.push_back(i);   
    
    // Construct v1 from subrange in v.
    std::vector<int> v1(v.begin() + 4, v.end() - 2);
    
    0 讨论(0)
提交回复
热议问题