指向向量的指针

5

我有这段代码:

#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;
}

我的编译器(G++)给我抛出了一些错误: test2.cpp:28:17: error: no match for 'operator<<' in 'std::cout << *(vecptr + ((unsigned int)(((unsigned int)i) * 12u)))' ...

出了什么问题?我该怎么修复它呢?

2个回答

9

这个程序还不完全正确。您需要初始化向量指针,然后给它一个大小并使用它。一个完整的可工作代码可能如下所示:

#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;
}

虽然我已经将大小定义为10,但您可以将其设置为变量。

6
您需要在此处取消引用vecptr,以获取基础向量:
cout << (*vecptr)[i] << endl;

您还需要初始化vecptr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接