我有这个代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我的编译器(G ++)给我一些错误:test2.cpp:28:17:错误:'std :: cout <<*中没有匹配'operator <<'(vecptr +((unsigned int)(((unsigned int) )i)*12u)))'...
怎么了?我该怎么办才能修复它?
该计划仍然不完全正确.你必须初始化向量指针,然后给它一个大小并使用它.完整的工作代码可以是,
#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;
}
Run Code Online (Sandbox Code Playgroud)
虽然我已经提到大小为10你可以把它变成一个变种.
您需要在vecptr此处取消引用以获取基础向量:
cout << (*vecptr)[i] << endl;
Run Code Online (Sandbox Code Playgroud)
您还需要初始化vecptr.