访问C++中的boost::变量向量的元素
Accessing elements of a boost::variant vector in C++
我想访问C++中向量的元素。我已经使用Boost_variant库生成了向量,因为我需要将int
和string
类型都存储为输入。
现在我想通过索引访问向量的元素,反过来,这样我就可以在它们上实现一个条件——类似于
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)
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C