
比如int a[] = { 0,1,3,5,6,4,2.... }
vector<int>v( a, a + sizeof( a ) / sizeof( a[0] ) )
2、动态添加就只有用push_back了
可以用resize预置vector的容量,这样就能免除push_back由于空间超过默认分配的定量内存时而重分配更大的一块新空间并把原内容重新拷过去所带来的效率损失,vector内部自动维护了一块定量的内存,这个空间可以用capacity()方法查看。
用stl的算法find_if,functor做谓词,感觉更简练一些#include <iostream>
#include <string>
#include <vector>
using namespace std
struct Table {
Table(const int n, const string&s, const int c):NUM(n),CI(s),count(c){}
int NUM
string CI
int count
}
class TheTable {
int NUM
public:
TheTable(int i):NUM(i) {}
bool operator()(Table&t) {
return t.NUM == NUM
}
}
int main () {
std::vector<Table>myvector
Table t0(1, "hello", 2), t1(2, "world", 3)
myvector.push_back(t0)
myvector.push_back(t1)
for (int i=0i<3++i) {
vector<Table>::iterator it = find_if(myvector.begin(), myvector.end(), TheTable(i))
if (it == myvector.end())
cout <<"Not found" <<endl
else {
std::cout <<"MyTable " <<(*it).CI <<'\n'
++(*it).count
}
}
return 0
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)