-
vector problem...
Theres a small problem here.Please read through the code.
Code:
#include <vector>
using namespace std ;
vector<char*> position ;
void pf(char* a)
{
//char* m = a ;
position.push_back(a);
}
int main(void)
{
pf("dog");
position.push_back("cat");
position.push_back("bear");
position.push_back("mouse");
position.push_back("horse");
sort(position.begin(),position.end()) ;
// why doesn't this sort work?? i want the cat, bear etc.. to be sorted alphabetically.
typedef vector<char*>::iterator VI ;
for( VI p = position.begin() ; p != position.end() ; ++p)
{
cout << *p << endl;
}
position.erase(position.begin() , position.end());
// I have already erased the vector called position here .
for( VI p = position.begin() ; p != position.end() ; ++p)
// now i want to
{ // print the elements again but it doesnt
// print at all.i know that its all gone
// but shouldn't it print garbage
//values???
cout << *p << endl;
}
}
-
1. The sorting criterion wont work for char* as they are pointers....and the comparison operators (like '<') dont operate that way for pointers.......use std::string to get the desired result
Code:
#include <vector>
#include <string>
#include <iostream>
using namespace std ;
int main(void)
{
vector<std::string> position ;
position.push_back("dog");
position.push_back("cat");
position.push_back("bear");
position.push_back("mouse");
position.push_back("horse");
sort(position.begin(),position.end()) ;
typedef vector<string>::iterator VI ;
for( VI p = position.begin() ; p != position.end() ; ++p)
{
cout << *p << endl;
}
}
2. The vector will not hold junk values.....erase gets rid of the elements and decreases the size of the container......so therefore no elements will be obtained from the iterators