在 C++ 中访问 boost::variant 向量的元素

Accessing elements of a boost::variant vector in C++

我想访问 C++ 中向量的元素。我使用 Boost_variant 库生成了向量,因为我需要将 intstring 类型都存储为输入。

现在我想通过索引 访问向量 的元素,然后反向访问,以便我可以对它们实施条件 - 类似于:

for (int i = last_element_of_vector, i >=0, i--){
     if (myvec[i] == 0 && myvec[i-1] == 1){
         *do something*
     }
}

我似乎只能找到在向量上循环的迭代器,并打印出没有任何可以访问元素的索引 i 的元素。

我的MWE如下:

#include <iostream>                         
#include <sstream>                           
#include <string>                           
#include <vector>                           
#include <boost/filesystem.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/variant.hpp>                

#include <boost/range/adaptor/reversed.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/assign.hpp>
#include <algorithm>

using namespace std;
using namespace boost::adaptors;
using namespace boost::assign;

typedef boost::variant<std::string,int> StringOrInt;

int main()
{
    vector<StringOrInt> bools; 
    bools += 0, 0, 0, 0, 1, 0, 1, 1, 1, 1;

    boost::copy(
                bools | reversed,
                std::ostream_iterator<StringOrInt>(std::cout, ", "));

    return 0;
}

main 中的最后几行仅打印出向量中的元素 bools 而实际上没有提供访问元素的索引。

提前致谢!

for 循环有许多确实 错误。我修复了下面的问题。

您应该创建一个变体以从变体中获取一些整数值:

struct as_int_visitor : boost::static_visitor<int> {
    int operator()(std::string const& s) const { return std::stoi(s); }
    int operator()(int i)                const { return i; }
};

使用方法如下:

int as_int(StringOrInt const& v) {
    return apply_visitor(as_int_visitor{}, v);
}

演示

Live On Coliru

#include <iostream>                         
#include <boost/assign/std/vector.hpp>
#include <boost/assign.hpp>
#include <boost/variant.hpp>                

#include <algorithm>

using namespace std;
using namespace boost::assign;

typedef boost::variant<std::string,int> StringOrInt;

struct as_int_visitor : boost::static_visitor<int> {
    int operator()(std::string const& s) const { return std::stoi(s); }
    int operator()(int i)                const { return i; }
};

int as_int(StringOrInt const& v) {
    return apply_visitor(as_int_visitor{}, v);
}

int main()
{
    vector<StringOrInt> values; 
    values += 0, 3, 4, 6, "42", 0, 1, 1, 1, 1;

    for (int i = values.size()-1; i > 0; --i) {
        std::cout << "At #" << i << " lives " << values[i] << " (evaluates to " << as_int(values[i]) << ")";

        if (as_int(values[i]) == 0 && as_int(values[i-1]) == 1){
            std::cout << " HIT\n";
        } else 
            std::cout << "\n";
    }
}

打印:

At #9 lives 1 (evaluates to 1)
At #8 lives 1 (evaluates to 1)
At #7 lives 1 (evaluates to 1)
At #6 lives 1 (evaluates to 1)
At #5 lives 0 (evaluates to 0)
At #4 lives 42 (evaluates to 42)
At #3 lives 6 (evaluates to 6)
At #2 lives 4 (evaluates to 4)
At #1 lives 3 (evaluates to 3)