[英]How do I change a vector to a vector of pointers in C++?
我一直遇到這個問題,我似乎找不到任何可以幫助我的資源。
基本上,我必須在這個 function 中將vector<User>
更改為vector<User*>
:
void promptUserAction(vector<User> &players, int playernumber, const Room rooms[], string &strCh,BadGuy bad)
{
// tell user where they are and describes the room
cout << (players)[playernumber] << " you are currently in " << rooms[(players)[playernumber].getIndexofCurrentRoom()]
<< endl;
if ((players)[playernumber].getIndexofCurrentRoom()==bad.getIndexCurrentRoom())
{
cout<<"There is a bad guy ("+bad.getName()+") also in the room."<<endl;
}
//prompt user for choice
cout << "What would you like to do?" << endl << "**********************" << endl;
cin >> strCh;
}
我不知道如何在我的main()
function 中正確調用 function。
do {
promptUserAction(players, User::IndNextUser, rooms, UserAction, badGuy1);
每當您引用它時,都無需像(players)
那樣將players
參數括在括號中。 將(players)[playernumber]
更改為players[playernumber]
。
無論如何,您顯示的代碼中沒有任何內容需要vector<User*>
,那么您為什么認為需要這種轉換? 如果你真的需要它(在你沒有顯示的代碼中),那么將vector<T>
轉換為vector<T*>
的唯一方法是創建一個新的vector
並推送第一個vector
的地址其中的元素,例如:
vector<T> vec;
...
std::vector<T*> dest;
dest.reserve(vec.size());
for(auto &elem : vec) {
dest.push_back(&elem);
}
或者:
vector<T> vec;
...
std::vector<T*> dest(vec.size());
std::transform(vec.begin(), vec.end(), dest.begin(),
[](auto &elem){ return &elem; }
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.