std::vector删除第一项
时间: 2024-04-08 09:26:02 浏览: 122
要删除std::vector中的第一项,可以使用erase()函数。erase()函数接受一个迭代器参数,指定要删除的元素位置。对于std::vector来说,可以使用begin()函数获取第一个元素的迭代器,然后将其作为参数传递给erase()函数。
下面是删除std::vector中第一项的示例代码:
```
std::vector<int> vec = {1, 2, 3, 4, 5};
vec.erase(vec.begin());
```
这样就会删除std::vector中的第一项。注意,如果std::vector为空,调用erase()函数会导致未定义行为。因此,在删除之前最好先检查std::vector是否为空。
相关问题
std::vector 取倒数第二个
要取std::vector的倒数第二个元素,可以使用rbegin()和逆迭代器。rbegin()指向末尾的下一位置,其存储的元素是末尾元素的值。所以,可以使用*(m.rbegin()+1)来获取倒数第二个元素的值。\[2\] 例如:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> m = { 1,2,3,4 };
int x = *(m.rbegin() + 1);
cout << x << endl; // 输出3
return 0;
}
```
在这个例子中,我们定义了一个vector m,并初始化为{1,2,3,4}。然后,使用rbegin()和逆迭代器来获取倒数第二个元素的值,并将其赋给变量x。最后,输出x的值,结果为3。
#### 引用[.reference_title]
- *1* [vector 删除和插入](https://blog.csdn.net/WWIandMC/article/details/108953380)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [c++ vector](https://blog.csdn.net/u013248806/article/details/78165044)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
std::vector<std::string> 截取字符串到结尾
std::vector<std::string> 是C++标准库中的容器,用于存储一组字符串。你可以使用它来动态地管理字符串的集合,并且可以方便地进行插入、删除和访问操作。
要截取字符串到结尾,你可以使用std::string的substr函数来实现。substr函数接受两个参数,第一个参数是起始位置的索引,第二个参数是要截取的子字符串的长度。如果只指定起始位置而不指定长度,则截取从起始位置到字符串结尾的所有字符。
下面是一个示例代码,演示了如何将一个字符串截取为多个子字符串,并将它们存储在std::vector<std::string>中:
```cpp
#include <iostream>
#include <vector>
#include <string>
int main() {
std::string str = "Hello, world! This is a test string.";
std::vector<std::string> substrings;
// 截取字符串到结尾
while (!str.empty()) {
substrings.push_back(str);
str = str.substr(1); // 从索引1开始截取到结尾
}
// 输出截取后的子字符串
for (const auto& substring : substrings) {
std::cout << substring << std::endl;
}
return 0;
}
```
运行上述代码,你将得到以下输出:
```
Hello, world! This is a test string.
ello, world! This is a test string.
llo, world! This is a test string.
lo, world! This is a test string.
o, world! This is a test string.
, world! This is a test string.
world! This is a test string.
world! This is a test string.
orld! This is a test string.
rld! This is a test string.
ld! This is a test string.
d! This is a test string.
! This is a test string.
This is a test string.
This is a test string.
his is a test string.
is is a test string.
s is a test string.
is a test string.
is a test string.
s a test string.
a test string.
a test string.
test string.
test string.
est string.
st string.
t string.
string.
string.
tring.
ring.
ing.
ng.
g.
.
```
阅读全文