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

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

本文关键字:向量 元素 变量 访问 中的 boost C++      更新时间:2023-10-16

我想访问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;
}

其中主中的最后几行仅打印出向量CCD_ 3中的元素,而没有实际提供访问这些元素的索引。

提前感谢!

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);
}

演示

在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 << " HITn";
        } 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)