问题描述
我有这个向量
std::vector<int> vec = {3,4,5,5};
我想检查向量中元素之间的相等性。在这种情况下,5 等于 5。我想将这些元素存储在另一个向量中,并将它们的位置(偏移量)保存在另一个变量中。
编辑://这不起作用
std::vector<int> vec = {3,5};
std::vector<int> store;
std::vector<int> offset;
int len = vec.size();
for(int count = 0; count + 1 < len; count++)
{
if(vec.at(count) == vec.at(count + 1))
{
store.push_back(vec.at(count));
offset = count;
}
}
输出应该是:
store = {5,5};
offset.at(0) = 2;
offset.at(1) = 3;
解决方法
这将计算重复次数,但不会计算相邻次数。
int main()
{
std::vector<int> vec = {3,4,5,7,8,8};
std::vector<int> store;
std::vector<int> offset;
int pos {0};
for (auto v : vec)
{
int c = std::count(vec.begin(),vec.end(),v);
if (c > 1) {
store.push_back(v);
offset.push_back(pos);
}
++pos;
}
for (auto v : store)
std::cout << "Repeated: " << v << std::endl;
for (auto v : offset)
std::cout << "Offsets: " << v << std::endl;
return 0;
}