首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

Vector声明限定元素数目的话,添加元素的个数就不能超过这个值吗?解决思路

2013-10-21 
Vector声明限定元素数目的话,添加元素的个数就不能超过这个值吗?#include iostream#include vector#in

Vector声明限定元素数目的话,添加元素的个数就不能超过这个值吗?


#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Point
{
public:
int id;
char *context;
double scroe;
Point(int i,char *j,double d)
{
id = i;
context = j;
scroe = d;
};//要不要这个分号,貌似都可以。
Point(){};
};
vector<Point> cities;//没有指定cities有几个元素。这样程序没有问题、
//vector<Point> cities(1);这样声明:vector<Point> cities[2],程序编译通过,运行时崩溃,怎么回事啊。
void add_points(Point sentinel)
{
cities.push_back(sentinel);
}
void main(void)
{
Point mypoint0(0,"test0",0.1);
add_points(mypoint0);//调用push_back()一次就可以增加一个vector元素。

Point mypoint1(1,"test1",0.2);
add_points(mypoint1);
Point mypoint2(2,"test2",0.3);
add_points(mypoint2);
cout<<"the length of vector is "<<cities.size()<<endl;//调用size()求vector的长度
for (unsigned int i=0;i<cities.size();i++)
{
cout<<"id: "<<cities[i].id<<"  context: "<<cities[i].context<<"  scroe: "<<cities[i].scroe<<endl;
//vector可以用下标操作符[i]来操作。跟数组类似。
}
}



这样声明:vector<Point> cities[2],程序编译通过,运行时崩溃,怎么回事啊。

[解决办法]
vector<Point> cities(1);
---这种是声明一个vector<Point>对象,并初始化一个值1给这个对象,这要求1能转换成Point对象,否则有问题。
vector<Point> cities[2],程序编译通过,运行时崩溃,怎么回事啊。
---这个声明vector<Point>一个数组,这个数组共有2个vector<Point>对象,当你使用时,你要指定你向哪个vector<Point>对象里push_back元素,否则就会内存错误

热点排行