包含用户定义类型指针的C ++向量

时间:2011-09-21 17:58:24

标签: c++ vector iterator containers qt-creator

我对此代码有疑问:

struct document_type_content
{
    long long m_ID;
    QString m_type_name;
};

std::vector<QString> document_type::get_fields_by_name(e_doc_type) const
{
    std::vector<QString> tmp;
    std::vector<document_type_content*>::iterator it = m_table_data.begin(),
            it_end = m_table_data.end();

    for ( ; it != it_end; ++it) {
        document_type_content* cnt = *it;
        tmp.push_back(cnt->m_type_name);
    }
}

我正在为项目使用QtCreator,它给了我以下错误(对于行,初始化迭代器的行):

error: conversion from '__gnu_cxx::__normal_iterator<document_type_content* const*, std::vector<document_type_content*, std::allocator<document_type_content*> > >' to non-scalar type '__gnu_cxx::__normal_iterator<document_type_content**, std::vector<document_type_content*, std::allocator<document_type_content*> > >' requested

这可能是一个简单的问题,无论如何,不​​是我:)。

非常感谢提前。

1 个答案:

答案 0 :(得分:5)

因为你的函数是常量,所以你只能持续访问你的类的this指针。这样可以持续访问您的向量。你需要从向量中获得const_iterator

这应该可以解决问题:

std::vector<QString> document_type::get_fields_by_name(e_doc_type) const
{
    std::vector<QString> tmp;
    std::vector<document_type_content*>::const_iterator it = m_table_data.begin(),
            it_end = m_table_data.end();

    for ( ; it != it_end; ++it) {
        document_type_content* cnt = *it;
        tmp.push_back(cnt->m_type_name);
    }
}