c++


Is this a legitimate way to find the position of an element in a vector? [duplicate]


This question already has an answer here:
Obtaining item index in ranged based for on vector
2 answers
I have the following loop in my code:
for (const auto& item : vec) {...}
In order to find the position of item in vec, I do:
size_t pos = ((size_t)&item-(size_t)vec.data())/sizeof(item);
But it feels kinda "C" (in opposed to "C++").
I know that I can achieve this purpose if I change my loop-format to either one of the following:
for (size_t i = 0; i < vec.size(); i++) {...}
for (auto it = vec.begin(); it != vec.end(); it++) {...}
But I would like to refrain from doing this.
Bottom line questions:
Is my method guaranteed by the language standard?
Is there a more "C++" way to do this without changing the loop-format?
Thank you.
But I would like to refrain from doing this.
Looping over an index/iterator is the exact thing you need here. Why would you refrain from doing that?
Is my method guaranteed by the language standard?
Just the fact that you have to ask this question to makes your method undesirable compared to a index/iterator loop. Regardless, I cannot see any reason why your method should fail.
Is there a more "C++" way to do this without changing the loop-format?
The most idiomatic C++ way is looping over an index/iterator. If you want a fancier version of that, you can wrap the logic in an higher-order function that provides the item as well:
template <typename Container, typename F>
void for_each_with_index(Container&& c, F&& f)
{
for(std::size_t i = 0; i < c.size(); ++i)
{
f(c[i], i);
}
}
Usage:
std::vector<item> v{/* ... */};
for_each_with_index(v, [](auto& item, std::size_t index)
{
/* ... */
});
live example on wandbox
You don't need to cast your types as you did in your example:
size_t pos = ((size_t)&item-(size_t)vec.data())/sizeof(item);
You can do pointer arithmetics more simplier as follows:
#include <iostream>
#include <vector>
int main() {
std::vector<int> test { 0, 1, 2, 3, 4, 5, 6 };
for(const auto& elem : test) {
const auto pos = &elem - test.data();
std::cout << "Element at position " << pos << " is: " << elem << std::endl;
}
return 0;
}
The reason it works because the type of &elem is const int* and the returning type of test.data() is int* so the pointer arithmetics works fine on them.
Note: if you forget the reference operator (&) in you range-based for loop the example above won't work:
for(const auto elem : test) { /* ... */ } // Warning: elem is a copy!
If you are really dying to do this in C++ without changing the loop format substantially, considering incorporating cpp itertools: https://github.com/ryanhaining/cppitertools/blob/master/README.md. It's your only hope!
vector<int> vec{2, 4, 6, 8};
for (auto&& e : enumerate(vec)) {
cout << e.index
<< ": "
<< e.element
<< '\n';
}
It provides lots more tools, drawing inspiration from python which is known for having very nice ways of iterating. You can also iterate over two same size vectors together, de-nest nested for loops, etc.
Strictly speaking, you can also implement enumerate yourself. It's not that difficult but it is quite a few lines of boilerplate.

Related Links

Finding the length of a C style char * string in c++ [duplicate]
How to draw square on the button at the center using OpenGL?
How to use pthread to write a C++ class like “boost::shared_mutex”
Undefined reference to a superclass' virtual function
How many ways can fill in HxW rooms with 2x1 tatami mats? [closed]
CMake add_subdirectory not invoking the child CMakeLists.txt
How to explicitly get linear indices from arrayfire?
cppunit throws std::bad_alloc after upgrading gcc to 5.4.0
Program compiles but I think switch is ignored.
multiplication of two integer arrays
get and set Enum variable inside a class?
How to use make “using” keyword within a method to accept it as class level
std::array-like class copy constructor
Access violation when using delete
C++ SFML compile error + install
Resizing 2D vector C++, Setting to 0

Categories

HOME
react-native
gnuplot
slickgrid
loops
raster
environment-variables
statistics
autodesk-forge
https
datatable
metal
conditional
q-learning
google-vr
protege
translate
mit-scratch
spring-aop
mupdf
affinity
angularjs-ng-route
drupal-modules
jquery-gmap3
spring-boot-actuator
image-comparison
cdb
python-datetime
entity-relationship
indexoutofrangeexception
preview
endpoints-proto-datastore
hibernate-criteria
dsolve
ireport
affiliate
kafka-python
neoscms
chmod
legacy
basic4android
bootstrapping
predict
jenkinsfile
reddit
cartography
pywinusb
autocorrect
xquery-sql
virsh
silent-installer
fluentbootstrap
invoke
generated
equation
libtool
simplehttpserver
nsoutlineview
powershell-tools
azure-webjobssdk
android-runtime
review-board
pubsubhubbub
nsthread
throttle
typing
frontpage
gridster
javascript-globalize
max-heap
assignment-operator
hottowel
busy-waiting
acl2
fswatch
jaxb2-maven-plugin
apache-roller
determinants
spool
arbitrary-precision
deface
nools
pixate
triples
linq-to-lucene
apiaxle
styledtext
toplink
dbase
scite
filtered-lookup
stackmob
wsimport
opengl-es-1.1
ipad-2
iphone-4
happstack
c89
bionic
expandoobject
soaplite
cloning
ant4eclipse
dynamic-css
progressive-enhancement

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App