简体   繁体   中英

Iterating over a vector containing pointers in c++

I got a function that accepts a pointer to a rapidjson::Value type and stores the item at that location into a rapidjson::Value of type kArrayType.

void addBlock(rapidjson::Value* block) {
    blocksArray.PushBack(*block, allocator);
}

This function works as expected.

To extend this I want to add a function that can take a vector of these pointers as an input. I tried this doing:

void addBlocks(std::vector<rapidjson::Value*> blocks) {
    for (const rapidjson::Value& block : blocks) {
        blocksArray.PushBack(*block, allocator);
    }
}

This does not work however. It gives me two red waves in Visual Studio.

The first one beneath block in the parameter declaration of the function, saying:

C++ no suitable constructor exists to convert from to...

And the second one beneath the * in the call to PushBack() , saying:

C++ no operator matches these operands operand types are: * const rapidjson::Value

My guess is that I am doing something very basic wrong that I am just missing.

It seems you are doing a copy, so why not use some std algorithm?

void addBlocks(std::vector<rapidjson::Value*> blocks) {
    std::transform(
        blocks.begin(),
        blocks.end(),
        std::back_inserter(blocksArray),
        [](rapidjson::Value* ptr){ return *ptr; });
}

Your vector contains pointers. Those cannot be automatically converted to references. The loop variable needs to be a reference of a pointer:

for (rapidjson::Value *& block : blocks)
{
     blocksArray.PushBack(*block, allocator);
}

Quite sure this is what "auto" would do under the hood (if the compiler doesn't entirely optimize it away).

Not sure it would allow you to keep the "const". It didn't when I tried this with ints.

You can use auto keyword to iterate on blocks vector:

for (auto block : blocks) { 
   ... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM