创建一个新的 C++ 子向量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9705441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:12:01  来源:igfitidea点击:

Creating a new C++ subvector?

c++vector

提问by John Smith

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 vector with pointers or do I have to push_back all the intermediary values I need?

假设我有一个值为 [1,2,3,4,5,6,7,8,9,10] 的向量。我想创建一个新的向量,例如,[5,6,7,8]。我想这只是用指针创建向量的问题,还是我必须推回我需要的所有中间值?

回答by hmjd

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

其中之一std::vector的构造函数接受范围:

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

回答by Flexo

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

这很容易做到std::valarray而不是向量:

#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.

它需要 valarray 的“切片”,比向量更通用。

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

回答by Luchian Grigore

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

你不必使用push_back,如果你不想,你可以使用std::copy

std::vector<int> subvector;
copy ( v1.begin() + 4, v1.begin() + 8, std::back_inserter(subvector) );

回答by Taylor Southwick

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

~

~