-1

for example how can i read just the first character of the first string:

vector <string> vec= {"aa","ab","abc","efg"};

Thank you.

  • 4
    like `vec[0][0]` – asmmo Jun 08 '20 at 16:22
  • `vec.front().front()` should also do it. But I'm not sure what you're really asking. – Fred Larson Jun 08 '20 at 16:25
  • 5
    I see that you need a c++ book not just an answer. see https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – asmmo Jun 08 '20 at 16:25
  • If you know how to reference a single element of your vector, you have a string. If you know how to reference a single element of a string, you have a character. Chain the two together, and baby? You got a stew. – JohnFilleau Jun 08 '20 at 16:49

2 Answers2

0

You can read it like this:

std::vector <std::string> vec = { "aa","ab","abc","efg" };
std::vector<char> result;
for (auto it = vec.begin(); it != vec.end(); ++it)
{
    result.push_back((*it)[0]); // (*it)[0] == vec[i][0]
}

Now result is a vector of first elements of each string

NixoN
  • 661
  • 1
  • 6
  • 19
  • That would be an iterator loop. An index loop, range-for loop, or [`std::transform`](https://en.cppreference.com/w/cpp/algorithm/transform) algorithm could all accomplish this as well. Hard to say what the OP is really trying to accomplish. – Fred Larson Jun 08 '20 at 16:30
  • Yeap, I know. Provided example of code for better understanding – NixoN Jun 08 '20 at 16:34
0

A vector just stores stuff you put in it, in this case, std::strings. To access the first element of a vector, as you said, there are multiple ways of doing that. The easiest, if you are used to arrays, is just using []:

std::string myString = myVector[0]; // store the first string of myVector

The second question is, how to access a character of a string, again, there are multiple ways of doing that, but again you can use []:

char myChar = myString[0]; //store the first character of myString

Also tip: It is generally frowned upon to use using namespace std;

Mikdore
  • 699
  • 5
  • 16