我想在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*
}
}
我似乎只能在向量上找到带有循环的迭代器,并打印出没有任何索引的元素,可以访问这些元素。
我的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
中的元素,而不实际提供访问元素的索引。
提前致谢!
答案 0 :(得分:1)
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)