Getting rid of empty indices in a vector

Hi guys,

So i'm working on a client/server application and in server i have this: std::vector<Client*> *clients; and i'm using client->push_back(*clientA) to add objects in it. Once client ends connection i clear data of that client in vector. So lets say i have 10 clients in vector and client number 3-5-8 disconnects. What i wanna do is remove those objects from vector and push other ones near to index 0 so that the next client i add will be placed at index 7 instead of 10. Is that possible ?
you could (i think) reverse-iterate through the vector and check each client number. when you come across a relevant client to delete erase this element. and remember to free up any corresponding memory.
Thanks for your reply. I figured that if i use vector::erase() it will automatically change position of rest of objects which will reduce size of vector. Problem solved.
cool. are you reverse-iterating too? This ensures you don't iterate through something that isn't there anymore :)
Oh you're right if both 4th and 5th clients disconnects at the same time i wont be able to erase 5th in first loop since it'll be actually 4th after erasing 4th. Thanks! :)
Erase–remove idiom: https://en.wikipedia.org/wiki/Erase-remove_idiom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
#include <iterator>

struct client { client( /* ... */ ) { /* ... */ }  /* ... */ };

int main()
{
    std::vector< std::unique_ptr<client> > clients ;
    for( int i = 0 ; i < 10 ; ++i ) clients.push_back( std::make_unique<client>( /* ... */ ) ) ;

    for( int i = 0 ; i < 10 ; i += 2 ) clients[i] = nullptr ;
    for( const auto& ptr : clients )
        if(ptr) std::cout << ptr.get() << ' ' ; else std::cout << "<nullptr> " ;
    
    // erase-remove
    clients.erase( std::remove( std::begin(clients), std::end(clients), nullptr ), std::end(clients) ) ;
    
    std::cout << "\n\nafter erase-remove: " ;
    for( const auto& ptr : clients )
        if(ptr) std::cout << ptr.get() << ' ' ; else std::cout << "nullptr " ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/c6e061aabfa9dcf6
Topic archived. No new replies allowed.