Whale Talk vector<char> and vector<std::string> not interchangeable? C++

learn-cpp/5-vectors/whale.cpp at master · Codecademy/learn-cpp · GitHub

I’ve been trying to do whale talk in C++ for the longest time and then I found something. Maybe I’m not understanding this correctly…

#include <iostream>
#include <vector>
#include <string>

int main() {
  std::string input = "a whale of a deal!";
  std::vector<char> vowels = {'a','e','i','o','u'};
  std::vector<char> result;
  // more code...

I got the main part of the code correct. However, how come we can’t use vectorstd::string? I had it like that originally since that’s how the previous section had us do, but this time I got massive errors. The moment I changed it to vector everything worked perfectly. How?

And on the flip side, how come we can’t substitute char for std::string for the input string?

Can someone help me understand this? I’m very confused and would really like to figure this out before moving on! Any help is greatly appreciated!

Yes, a char and a string are inherently different data types in C++, there’s a lot of detail to how they are and why it doesn’t make sense for them to be interchangeable. However, you can always cast a char as a string so you should consider that as well.

Some differences:

  • size in memory
  • stack vs heap allocation
  • chars are basically ascii
  • strings can deal with utf-8
  • string have a lot of similarity to dynamic arrays (std::vectors) in terms of memory allocation

Casting can be as simple as

char c = 'a';
std::string s = std::string(1, c);

technically not a cast but virtually can be used the same way when necessary.