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

WT save file dialog window?
Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted
Why does this code give me an infinite loop?
Problems pasing a matrix to my method
what happened when function return
use the method of extended class and of derived
PushBack (push_back()) elements of QStringList to vector<string>
Create a class using objects of another class
C++ char*[] to char** conversion
C++11 constructor inheritance through variadic templates
SetNamedSecurityInfo execution restarts system
expected unqualified-id before ')' token [closed]
How to measure the time of 100 executions of the program? [closed]
How can I convert a list of .png to a list of pdf in makefile?
How to get the real and imaginary parts of a complex matrix separately in CUDA?
Handling TCP connection failure in c++ cassandra client using a thrift wrapper library

Categories

HOME
angular
web
knn
environment-variables
sql-server-2005
ignite
monitoring
python-3.6
axis2
iis-8
ieee
dynamics-ax-2012
navbar
category
amazon-route53
web-component
markup
touch
jqxwidgets
hal
bing-api
ireport
mahapps.metro
hipchat
wasapi
regex-negation
javapoet
rrd4j
webmin
sqlcmd
hana-cloud-platform
nsubstitute
gooddata
digestive-functors
oracle-sql-data-modeler
spring-cloud-sleuth
google-console-developer
libphonenumber
roc
paypal-adaptive-payments
zlib
canvas-lms
sp-executesql
tinyxml2
mypy
android-gson
angularjs-service
schemaless
libtool
sqlcommand
code-signing-entitlements
type-systems
android-runtime
windows-firewall-api
sequencing
python-wheel
reportviewer2008
xlconnect
test-and-target
struts2-jquery-grid
sparklines
command-line-tool
nameerror
gcdasyncsocket
gstat
window-position
nstablecolumn
dynamic-ip
cordova-chrome-app
apache-tomee
zurb-joyride
jform-designer
complete.ly
topcoat
hierarchyid
perl-critic
emacs-dirtree
sts-securitytokenservice
.lrc
scopes
mfi
actinic
testdriven.net
iphone-sdk-4.1
vtl
viewexpiredexception
libjson
application-design
urldecode
platform-independence
pia

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