在基于范围的for循环中查找具有连续内存的序列中元素的位置 在一个基于C++的范围内运行循环,在 STD::vector < /COD>或C数组。我最初的猜测是否定的,除非你使用指针和指针数学,但只是想检查一下。我想做的是检查相邻的元素,以检查它们如何影响我当前的代码。我还知道向量中还有更多关于项的内容。代码将类似于: std::vector<Item> v; // do work for(auto& item : v) { //do more work auto pos = //some way to find get the position if(/*pos is the first position*/) { process(item, pos+1); } else if(/*pos is the last position*/) { process(item, pos-1); } else { process(item, pos-1, pos+1); } } std::vector v; //工作 用于(自动项目:v(&E) { //多做点工作 auto pos=//找到位置的方法 如果(/*位置是第一个位置*/) { 流程(项目,pos+1); } 如果(/*位置是最后一个位置*/),则为else { 过程(项目,pos-1); } 其他的 { 流程(项目、pos-1、pos+1); } }

在基于范围的for循环中查找具有连续内存的序列中元素的位置 在一个基于C++的范围内运行循环,在 STD::vector < /COD>或C数组。我最初的猜测是否定的,除非你使用指针和指针数学,但只是想检查一下。我想做的是检查相邻的元素,以检查它们如何影响我当前的代码。我还知道向量中还有更多关于项的内容。代码将类似于: std::vector<Item> v; // do work for(auto& item : v) { //do more work auto pos = //some way to find get the position if(/*pos is the first position*/) { process(item, pos+1); } else if(/*pos is the last position*/) { process(item, pos-1); } else { process(item, pos-1, pos+1); } } std::vector v; //工作 用于(自动项目:v(&E) { //多做点工作 auto pos=//找到位置的方法 如果(/*位置是第一个位置*/) { 流程(项目,pos+1); } 如果(/*位置是最后一个位置*/),则为else { 过程(项目,pos-1); } 其他的 { 流程(项目、pos-1、pos+1); } },c++,c++11,for-loop,c++14,C++,C++11,For Loop,C++14,我不关心迭代器对象是第一个对象、最后一个对象还是中间对象。一种方法是使用搜索元素。然后,如果找到了元素,可以使用计算索引 std::vector<int> myVec; int valToFind = 5; auto it = std::find(myVec.begin(), myVec.end(), valToFind); if (it != myVec.end()) { int index = std::distance(myVec.begin(), it); } 查

我不关心迭代器对象是第一个对象、最后一个对象还是中间对象。

一种方法是使用搜索元素。然后,如果找到了元素,可以使用计算索引

std::vector<int> myVec;
int valToFind = 5;

auto it = std::find(myVec.begin(), myVec.end(), valToFind);
if (it != myVec.end())
{
    int index = std::distance(myVec.begin(), it);
}

查找索引的两种方法(在
std::find
之后)都是
O(1)
,因为向量是随机访问容器。

对于具有连续内存的序列:

for(const auto& element : sequence) {
    // If the sequence has a member data()
    // std::array, std::vector or std::string 
    auto index = &element - sequence.data();

    // If the sequence is an array
    auto index = &element - sequence;

    // If the sequence supports operator []
    // All of above
    auto index = &element - &sequence[0];

    // Generally
    auto index = &element - &*std::begin(sequence);
}

你能详细说明一下你在获得这个职位后打算做什么吗
运算符-
对于vector这样的随机访问容器是定义良好且恒定的时间。请参阅这是副本(没有可接受的答案)的特例(连续内存)。这里提供的答案完全是多余的。我想你可以只做
&sequence[0]
,让它对vector、string、std::array和plain array起作用。这只会假设所有元素都是唯一的,我认为它对基于范围的for循环不起作用
for(const auto& element : sequence) {
    // If the sequence has a member data()
    // std::array, std::vector or std::string 
    auto index = &element - sequence.data();

    // If the sequence is an array
    auto index = &element - sequence;

    // If the sequence supports operator []
    // All of above
    auto index = &element - &sequence[0];

    // Generally
    auto index = &element - &*std::begin(sequence);
}