Home > C/C++, Italiano, Other > Converting a String to a Vector

Converting a String to a Vector

It has been a long while since I’ve posted a C or C++ tutorial, but here comes another one! I try to help with programming tips on various forums across the internet. I am a fluent English and Italian speaker, so naturally I work on forums of both languages. While browsing an Italian forum, I came across an interesting question. How does one convert a C++ string to a vector. I decided I would lend a hand, and it bears repeating on here.

Vectors can be used for various things in C++, but they are for the more advanced programmer really. They are not really necessary if it is not a complex program, but this tutorial could serve useful for many I’m sure.

I myself was at first puzzled by the question. I had never thought of a reason to do this and so, frankly, I never have. After some thought, it wasn’t too bad, but still an interesting concept. I’ll post the code below and then explain further below that. Comments are in both English and Italian. The reason being is what I previously mentioned about the original reason I wrote this code.

/**
* String to Vector Tutorial by Dennis M.
*
* un tutorial di microsonic.org
*
*/

// Include files ~ Includere i file
#include <string>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
// Declare Variables ~ Definire i varibili
string data = "one - uno";
vector<string> vect;

// Insert data into vector ~ Inserire l'informazione in il vector
vect.push_back(data);
data = "two - due";
vect.push_back(data);
data = "three - tre";
vect.push_back(data);

// Loop to view the contents of the vector ~ Loop per vedere i contenti di il vector
for(unsigned int i=0;i<vect.size();i++){
cout<< i << ": " << vect.at(i) << endl;
}

// Memory Management ~ Ci sicuriamo la memoria!
vect.clear();

return 0;
}

Now the code is pretty self-explanatory and the comments I think do a pretty good job. The only thing one may be perplexed about is where the functions and pointers come from. If you examine the documentation (header file?) for a vector, all is clearly defined. This example will also print the vector and clear it before it exits.

So I hope this post is of some service to someone and as usual, I have included the source and binaries in the post!

String to Vector Tutorial

Regards,
Dennis M.

Categories: C/C++, Italiano, Other Tags:
  1. September 14th, 2009 at 08:46 | #1

    Thanks much for this nice post.

  1. No trackbacks yet.