The*_*ere 1 c++ algorithm stl vector
你能告诉我如何使用STL算法进行以下操作吗?
// Create a vector of 50 elements, and assign elem value same as index value
std::vector<int> a(50);
for (int i = 0; i < a.size(); i++)
{
a[i] = i;
}
// Create another vector by copying a section of vector a
std::vector<int> b;
size_t ind = 20;
b.resize(a.size() - ind);
for (int i = 0; i < b.size(); i++)
{
b[i] = a[i+ind];
}
Run Code Online (Sandbox Code Playgroud)
本质上,我试图通过跳过a的第一个'ind'元素,从vector a创建一个新的向量b.
我可能会这样做:
std::vector<int> a(50);
// fill a with 0..N
std::iota(a.begin(), a.end(), 0);
size_t ind = 20;
// initialize `b` from elements of `a`:
std::vector<int> b{a.begin()+ind, a.end()};
Run Code Online (Sandbox Code Playgroud)
您可以使用std::copy第二部分,但对于手头的情况,我更喜欢b从迭代器初始化,就像我上面所做的那样.
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |