Get In The Shell
Get In The Shell

Reputation: 65

Conversion from vector<string> to non-scalar type string

I'm trying to assign a string with a string from a vector. I create the string and try to assign it the value of the index from the vector:

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 }

I get this error message:

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];
                                 ^

Any help will be appreciated.

Upvotes: 1

Views: 1797

Answers (1)

selbie
selbie

Reputation: 104524

You are passing your cards vector by pointer into your hand constructor. Pass it by reference instead:

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

Or alternatively, if you want to keep passing cards as a pointer, then you need to properly deference it to insert a value into it.

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

or

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

Upvotes: 3

Related Questions