2015-11-14 60 views
1

我試圖從矢量分配一個字符串與字符串。我創建的字符串,並嘗試從矢量分配給它的索引值:從矢量<string>轉換爲非標量類型字符串

1 #include "poker.h" 
2 #include <iostream> 
3 #include <stdlib.h> 
4 #include <time.h> 
5 #include <vector> 
6 #include <string> 
7 
8 hand::hand(std::vector<std::string>* cards) { 
9   cards_used = 0; 
10   cards_left = 52; 
11 
12   srand(time(NULL)); //Initialize random seed 
13 
14   //Card 1 
15   int rand_num = rand() % (cards_left - 1); //Set random number 
16 
17     //Set value and suit 
18   std::string temp = cards[rand_num]; //Problem here 
19   c1_value = std::stoi(temp.substr(0, 1)); 
20 } 

我收到此錯誤信息:

poker.cpp: In constructor ‘hand::hand(std::vector<std::basic_string<char> >*)’: 
poker.cpp:18:35: error: conversion from ‘std::vector<std::basic_string<char> >’ to non-scalar type ‘std::string {aka std::basic_string<char>}’ requested 
std::string temp = cards[rand_num]; 
           ^

任何幫助將不勝感激。

回答

3

您正在將您的cards矢量通過指針傳遞給您的手構造函數。按引用傳遞它,而不是:

hand::hand(std::vector<std::string>& cards) 

或者,如果你想保持路過cards爲指針,那麼你需要正確地尊重它插入值到它。

std::string temp = (*cards)[rand_num]; 

or 

std::string temp = cards->at(rand_num); 
+0

這工作,感謝您的幫助! – Daniel