Saturday, May 23, 2009

Using pscp to transfer file

To transfer file from unix to windows
pscp username@host:./file .\file
or with private key
pscp -i "private_key" username@host:./file .\file

To transfer file from windows to unix
pscp .\file username@host:./file

Wednesday, May 20, 2009

Delete string vector item with find_if function

To use find_if, we may need to supply c++ utility function such as less,
however, this function normally only support primitive, to support custom type we may need to supply own user function, below code show us how build the custom function.



// functional_bind1st.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
#include <strstream>

using namespace std;

class strequal
{
public:
strequal(char* ptr)
{
strcpy(str,ptr);
}
bool operator() (string& ptr)
{
if(!strcmp(str,ptr.c_str()))
{
return true;
}
else
{
return false;
}
}

private:
char str[100];

};

int main()
{
vector v1;
vector::iterator Iter;

int i;
for (i = 0; i <= 5; i++)
{
string abc;
std::strstream abc_stream;
abc_stream << i << '\0';
abc = abc_stream.str();
v1.push_back(abc);
}

cout << "The vector v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << (*Iter).c_str() ;
cout << ")" << endl;

char* data="1";

Iter = find_if(v1.begin(),v1.end(),strequal(data));
if(Iter!=v1.end())
{
v1.erase(Iter);
}

cout << "The vector v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << (*Iter).c_str() ;
cout << ")" << endl;

return 0;
}

Wednesday, May 6, 2009

Delete item in vector iterator loop

Most common mistake we face during we want to remove an iterator in vector loop is


for(iter = list.begin(); iter != list.end();++iter)
{
if(match(*iter))
{
list.erase(iter);
}
}


The correct way should be



for(iter = list.begin(); iter != list.end();)
{
if(match(*iter))
{
iter = list.erase(iter);
}
else
{
++iter;
}
}
or
list.erase(std::remove_if(list.begin(),
list.end(), match))