1

I have 3 maps with a string as key and a vector as value.

std::map<std::string, std::vector<int> >          m_attri;   ///< Attributes of type int
std::map<std::string, std::vector<double> >       m_attrd;   ///< Attributes of type double
std::map<std::string, std::vector<std::string> >  m_attrs;   ///< Attributes of type std::string

I have a function that resizes them all, calles SetNum()

void SetNum(size_t n)
{
    std::cout << "setting num: " << n << std::endl;
    m_num = n;
    for (auto attr : m_attri) {
        attr.second.resize(n, 0);
        std::cout<<attr.second.size();
    }
    for (auto attr : m_attrd) {
        attr.second.resize(n, 0.0);
        std::cout<<attr.second.size();
    }
    for (auto attr : m_attrs) {
        attr.second.resize(n, "");
        std::cout<<attr.second.size();
    }
    std::cout<<std::endl;
}

this all seems to work, when is say setnum(1), I get a bunch of 1s as output.

Now the problem lies here, I have another function called Set

template<typename T>
inline void AttributeContainer::Set(size_t node_idx, const std::string& name, T value)
{
    std::cout << GetNum() << node_idx << ',' << std::endl;
    if( node_idx >= GetNum()){
        SetNum(node_idx+1);
    }
    auto attr_kv = Attributes<T>().find(name);
    if (attr_kv != Attributes<T>().end()) {
        std::cout<<"Containersize: " << attr_kv->second.size() << ',' << "id:"<< node_idx<< std::endl;
        attr_kv->second.at(node_idx) = value;
        std::cout<<"ContainersizeDone: " << attr_kv->second.size() << std::endl;
    } else {
        throw std::runtime_error("AttributeContainer::Set(): attribute not found: " + name);
    }
}

node_idx is 0 and the vector is found. But it seems that the resize didn't work, because, altough I get output that confirms it is resized, i get a out_of_range exception from at and the line above shows that the size is 0. Now this is weird, as I thought that I succesfully resized them?

quantdev
  • 23,517
  • 5
  • 55
  • 88
Pinna_be
  • 4,517
  • 2
  • 18
  • 34

1 Answers1

4

In SetNum, you are iterating over your map by value (see this post)

Consequently, you are applying resize on copies of your stored vectors.

What you want is to use auto& :

void SetNum(size_t n)
{
    std::cout << "setting num: " << n << std::endl;
    m_num = n;
    for (auto& attr : m_attri) {
        attr.second.resize(n, 0);
        std::cout<<attr.second.size();
    }
    for (auto& attr : m_attrd) {
        attr.second.resize(n, 0.0);
        std::cout<<attr.second.size();
    }
    for (auto& attr : m_attrs) {
        attr.second.resize(n, "");
        std::cout<<attr.second.size();
    }
    std::cout<<std::endl;
}
Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88