C++ 指向向量的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8261620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pointer to vector
提问by icepopo
I've got this code:
我有这个代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr;
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
vecptr->push_back(temp);
}
veclen = vecptr->size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<vecptr[i]<<endl;
}
return 0;
}
My compiler(G++) throw me some errors: test2.cpp:28:17: error: no match for 'operator<<' in 'std::cout << *(vecptr + ((unsigned int)(((unsigned int)i) * 12u)))' ...
我的编译器(G++)给我抛出了一些错误: test2.cpp:28:17: 错误:在 'std::cout << *(vecptr + ((unsigned int)(((unsigned int) )i) * 12u)))' ...
What's wrong? What can I do to fix it?
怎么了?我能做些什么来修复它?
回答by Ajai
The program is still not completely right. You have to initialize the vector pointer and then give it a size and the use it. A full working code could be,
该程序仍然不完全正确。你必须初始化向量指针,然后给它一个大小并使用它。完整的工作代码可能是,
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr = new vector<string>(10);
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
(*vecptr)[i] = temp;
}
veclen = (*vecptr).size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<(*vecptr)[i]<<endl;
}
return 0;
}
Although I have mentioned the size as 10 you could make it a variant.
虽然我已经提到大小为 10,但您可以将其设为一个变体。
回答by Mark Byers
You need to dereference vecptr
here to get the underlying vector:
您需要在vecptr
此处取消引用以获取基础向量:
cout << (*vecptr)[i] << endl;
You will also need to initialize vecptr
.
您还需要初始化vecptr
.