Monday, July 15, 2013

set and vector in cpp

    std::set<char> terminalList = objTree->getAllTerminalList();
    std::vector<char> terminalVect(terminalList.begin(), terminalList.end());

C++, copy set to vector

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
Or, you could use the std::vector range constructor:
std::vector<double> output(input.begin(), input.end()); 



Return by value
1
2
3
4
5
int DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // A copy of nValue will be returned here
} // nValue goes out of scope here
Return by reference
1
2
3
4
5
int& DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // return a reference to nValue here
} // nValue goes out of scope here
Return by reference is typically used to return arguments passed by reference to the function back to the caller. In the following example, we return (by reference) an element of an array that was passed to our function by reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// This struct holds an array of 25 integers
struct FixedArray25
{
    int anValue[25];
};
// Returns a reference to the nIndex element of rArray
int& Value(FixedArray25 &rArray, int nIndex)
{
    return rArray.anValue[nIndex];
}
int main()
{
    FixedArray25 sMyArray;
    // Set the 10th element of sMyArray to the value 5
    Value(sMyArray, 10) = 5;
    cout << sMyArray.anValue[10] << endl;
    return 0;
}
Return by address
1
2
3
4
5
int* DoubleValue(int nX)
{
    int nValue = nX * 2;
    return &nValue; // return nValue by address here
} // nValue goes out of scope here
Return by address is often used to return newly allocated memory to the caller:
1
2
3
4
5
6
7
8
9
10
11
12
13
int* AllocateArray(int nSize)
{
    return new int[nSize];
}
int main()
{
    int *pnArray = AllocateArray(25);
    // do stuff with pnArray
    delete[] pnArray;
    return 0;
}

No comments:

Post a Comment