c++使用 vector指针访问vector元素时,不能简单的类似于c中数组和指针的方式。需要使用迭代器。
int main()
{
vector<int> s;
vector<int> *p = &s;
s.push_back(1);
for (vector<int>::iterator it = p->begin(); it != p->end(); it++)
cout << *it<<endl; //使用迭代器,正确
cout << p[0] << endl; //错误
cout<< (*p)[0]<<endl; //正确
return 0;
}
参考:https://blog.youkuaiyun.com/fao9001/article/details/75006369
本文探讨了在C++中使用vector时,为何不能直接使用指针访问元素,而应采用迭代器进行遍历。通过示例代码,详细解释了vector与迭代器的正确使用方法,以及如何避免常见错误。
1038

被折叠的 条评论
为什么被折叠?



