C++ - std::vector add, insert, remove, process, erase, swap, sort, clear

2. April 2013 08:00

 

Here is some examples of how to use std::vector with string for most of the common operations that can be performed on std::vector.

 

The following example assume the following has been declared

 

 

std::vector<std::string> vec;

 

 

Adding Items

vec.push_back("Item 1");
vec.push_back("Item 2");
vec.push_back("Item 3");
vec.push_back("Item 4");
vec.push_back("Item 5");

 

Adding Items to front

vec.insert(vec.begin(), "Front 2");
vec.insert(vec.begin(), "Front 1");

 

Remove Last Item

 

vec.pop_back();

 

 

Remove Last Item

 

vec.erase(vec.end());

 

 

Remove First Item

 

vec.erase(vec.begin());

 

 

Process All Items

for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
  printf("%s\n", it->c_str());
}

 

Process All Items

for(size_t i = 0; i < vec.size(); i++)
{
  printf("%s\n", vec[i].c_str());
}

 

Reverse The Order - Note you can also just run the above backwards instead.

for(size_t i = 0; i < vec.size() / 2; i++)
{
  std::string tmp = vec[i];
  vec[i] = vec[vec.size() - i - 1];
  vec[vec.size() - i - 1] = tmp;
}

 

Sorting

std::sort(vec.begin(), vec.end());

 

Find and Remove an item

for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
  if (*it == "Item 2")
  {
    vec.erase(it);
    break;	//it is now invalud must break!
  }
}

 

Clear All Items

vec.clear();
E-mail Kick it! DZone it! del.icio.us Permalink


Adding emergency swap space to linux

6. January 2012 06:00

 

This is a quick guide to adding emergancy swap space to linux. Which is useful when you know a machine is going to run out memory. Or you need a lot of memory for a single task that cannot be completed without the extra memory.

 

Step 1

 

Login as root

 

Step 2

 

Create a new file of the size that you want to add using the following command. In this case 512 mbytes of space.

 

dd if=/dev/zero of=/extraswap1 bs=1024 count=512k

 

Step 3

 

Fix the permissions on the file so that only the creator can read / write to it.

 

chmod 0600 /extraswap1

 

Step 4

 

Turn it into a swap file and tell linux to turn on the extra space

 

mkswap /extraswap1

swapon /extraswap1

 

Step 5

 

If you want the swap to be enabled after the next reboot of the machine you will need to add the following line to /etc/fstab

 

/extraswap1 swap swap defaults 0 0

 

Finally

 

You can verify that it is working by either using free or by looking directly at the proc filesystem using cat /proc/swaps

E-mail Kick it! DZone it! del.icio.us Permalink