evazkj
10/31/2018 - 4:07 PM

C++ data structures

vector, string

#inlcude <bdlb_tokenizer.h>
// https://bde.bloomberg.com/NonGit/Doxygen/bde_api_prod/
// Two kinds of delimiters:
//  Soft: adjacent delimiters are treated as one
//  Hard: adjacent deliieters are treated as multiple ones
bdld::Tokenizer tokenIt(line.c_str(), softDelims, hardDelims);
for ( ; tokenIt.isValid(); ++tokenIt) {
  bsl::cout << "token:" << tokenIt.token() << "\n";
}

Reserve memory for vector:

bsl::vector.reserve(<number of elements>)

Other initiation methods:

bsl::vector<bsl::string> vs2(10); // size is 10, each
// string is empty
bsl::vector<bsl::string> vs3(5, "hello");
// size is 5, each string
// is "hello"
bsl::vector<bsl::string> vs4(vs3); // vs4 is copy of vs3

Be careful about size_t! size_t is unsigned, doing arithmetic operation on it may be risky.

ARRAY:

Initiation: int evenNumbers[5] = { 0, 2, 4 }; // size 5, 0-filled int zeros[10] = {0}; // size 10, all set to 0

String

Compare

string.compare(string)
//output: 0, <0, >0

Initiation:

  • The preferred way of initiate string is to using
string hello{"hello"}

over

string hello("hello")

Array

best practice of passing an array to a function

void foo(int numbers[], size_t size);

Pass multi-dimensional array to a function:

void reverse(int matrix[][WIDTH])

It is different from:

int *matrix[]

The former indicate the memory is continuosly allocated.

#include <bdeut_stringref.h>
void tokenize(bsl::vector<bsl::string>& tokens, 
                       const bsl::string& input, 
                       const char *softDelims,
                       const char *hardDelims)
{
    BloombergLP::bdeut_StrTokenRefIter tokenIt(input.c_str(), softDelims, hardDelims);
    for (; tokenIt; ++tokenIt) {
        tokens.push_back(tokenIt());
    }
}