Jak*_*cki 6 c++ pointers vector
你好,我有一个向量:
vector<int> myCuteVector {1,2,3,4};
Run Code Online (Sandbox Code Playgroud)
现在我想以这样的方式创建一个子向量,它将包含来自 myCuteVector 的 2 个第一个元素,这样在修改子向量元素之后,myCuteVector 的元素也会改变。
伪代码:
vector<int> myCuteVector {1,2,3,4};
vector<int> myCuteSubVector = myCuteVector[0:2];
myCuteSubVector[0] = 5;
printf("%d", myCuteVector[0]) //would print also 5;
Run Code Online (Sandbox Code Playgroud)
有可能实现吗?
您可以使用std::reference_wrapper. 那看起来像:
int main()
{
std::vector<int> myCuteVector {1,2,3,4};
std::vector<std::reference_wrapper<int>> myCuteSubVector{myCuteVector.begin(), myCuteVector.begin() + 2};
myCuteSubVector[0].get() = 5; // use get() to get a reference
printf("%d", myCuteVector[0]); //will print 5;
}
Run Code Online (Sandbox Code Playgroud)
或者你可以直接使用迭代器
int main()
{
std::vector<int> myCuteVector {1,2,3,4};
std::vector<std::vector<int>::iterator> myCuteSubVector{myCuteVector.begin(), myCuteVector.begin() + 1};
// it is important to note that in the constructor above we are building a list of
// iterators, not using the range constructor like the first example
*myCuteSubVector[0] = 5; // use * to get a reference
printf("%d", myCuteVector[0]); //will print 5;
}
Run Code Online (Sandbox Code Playgroud)
从 C++20 开始,您可以使用std::span:
std::vector<int> myCuteVector {1,2,3,4};
std::span<int> myCuteSubVector(myCuteVector.begin(), 2);
myCuteSubVector[0] = 5;
std::cout << myCuteVector[0]; // prints out 5
Run Code Online (Sandbox Code Playgroud)
现场演示:https : //wandbox.org/permlink/4lkxHLQO7lCq01eC。
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |