- push_back():将元素插入到vector的末尾。
vector<int> myvector; myvector.push_back(1); myvector.push_back(2);
- pop_back():从vector的末尾删除元素。
- size():返回vector中元素的数量。
- empty():如果vector为空,则返回true。
- clear():删除vector中的所有元素。
- front():返回vector的第一个元素。
- back():返回vector的最后一个元素。
- insert():将元素插入到vector中的指定位置。
vector<int> myvector {1, 2, 3}; myvector.insert(myvector.begin() + 1, 4); // myvector = {1, 4, 2, 3}
- erase():从vector中删除指定位置的元素。
vector<int> myvector {1, 2, 3}; myvector.erase(myvector.begin() + 1); // myvector = {1, 3}
-
min
min_element(wc.begin(), wc.end()) != wc.end()
- max
max=distance(t.begin(),max_element(t.begin(),t.end()));
max_element(wc.begin(), wc.end()) != wc.end()
struct Stu{
int xh;
int score;
};
stu.push_back({.xh=xh,.score=score})
cout << stu[i].xh << " " << stu[i].score << endl;
-
stable_sort(stu.begin(),stu.end(),cmp); bool cmp(Stu x,Stu y){ if( x.score==y.score)return x.xh<y.xh; else return x.score<y.score; }
-
find_if()(详解)
函数原型
template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
其中UnaryPredicate p是一个函数
bool isEven(int n)
{
return n % 2 == 0;
}
如果判断的值是变量则
struct Student{
string num;
string name;
string gender;
int age;
};
string targetNum;
cin >> targetNum;
auto it = find_if(stu.begin(), stu.end(), [&targetNum](const Student& s){ return findNum(s, targetNum); });
其中p为
[&targetNum](const Student& s){ return findNum(s, targetNum); }
bool findNum(const Student& s, const string& target)
{
return s.num == target;
}
if (it != v.end()) {
cout << "The first even number is " << *it << endl;
} else {
cout << "No even number found!" << endl;
}
auto f=[&targetNum](const Student& s){
return s.num == targetNum;
};
auto it = find_if(stu.begin(), stu.end(),f);
10.std::vector::assign()
是 std::vector
的一个成员函数,用于将新的元素替换掉当前的元素。该函数有多种重载形式,其中一种常用形式是:
std::vector<int> vec{1, 2, 3, 4, 5};
vec.assign(3, 0); // 将 vec 中的元素替换为 0, 0, 0
11
void printVector(const std::vector<int>& vec) {
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
}