How to Get Position of a Certain Element in Strings Vector, to Use It as an Index in Ints Vector

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
//old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

vectorstring::iterator - how to find position of an element

You can use std::distance for that:

auto pos = std::distance(vec.begin(), it);

For an std::vector::iterator, you can also use arithmetic:

auto pos = it - vec.begin();

Finding the index of a string inside a field of strings

arma does not support the storage of std::string within its data structures per Matrix types

The root matrix class is Mat, where type is one of:

  • float, double, std::complex, std::complex, short, int, long, and unsigned versions of short, int, long

In turn, Rcpp does not support the import or export of std::vector<std::string> into armadillo. Thus, the error.

The easiest way to find a string in this case is to loop through the vector and check each element. Alternatively, make a map and see if the key is within the map.

Loop string checking approach:

#include <Rcpp.h>

// [[Rcpp::export]]
std::vector<int> find_string_locs(std::vector<std::string> input_vector, std::string id)
{
std::vector<int> id_locs; // Setup storage for found IDs

for(int i =0; i < input_vector.size(); i++) // Loop through input
if(input_vector[i] == id) // check if input matches target
id_locs.push_back(i);

return id_locs; // send locations to R (c++ index shift!)
}

/***R
input_vector = c("stat","toad","stat","rcpp")
id = "stat"
find_string_locs(input_vector,id)
*/

The output is then:

[1] 0 2

Note the C++ index shift... Starts at 0 instead of 1 like in R.

Searching a vector for a string, and then find the position of the string in c++

Below is the working example. There is no need to store the string into a vector or search for the position of the string inside the vector because we can directly check if the read line is equal to the string to be searched for, as shown.

main.cpp

#include <iostream>
#include <fstream>

int main()
{

std::string line, stringtobeSearched = "Foo8854.txt";

std::ifstream inFile("input.txt");

std::ofstream outFile("output.txt");
if(inFile)
{
while(getline(inFile, line, '\n'))
{
std::cout<<line<<std::endl;
//if the line read is not same as string searched for then write it into the output.txt file
if(line != stringtobeSearched)
{
outFile << line << "\n";
}
//if the line read is same as string searched for then don't write it into the output.txt file
else
{
std::cout<<"string found "<<std::endl;//just printing it on screen
}


}
}
else
{
std::cout<<"file could not be read"<<std::endl;
}
inFile.close();
outFile.close();


return 0;
}

input.txt

file123.txt
Bob56.txt'
Foo8854.txt
file113.txt
Bob56.txt'
Foo8854.txt
file223.txt
Bob96.txt'
Foo8814.txt

output.txt

file123.txt
Bob56.txt'
file113.txt
Bob56.txt'
file223.txt
Bob96.txt'
Foo8814.txt

Index of vector of strings in c++

You can output the first index element through this process.

I have made a 2D vector and applied a for loop so each row of the vector's first element is printed.

#include <iostream>
#include <vector>

int main()
{
std::vector<std::string> vec = {"chemistry", "maths", "physics"};

for(int i=0;i<vec.size();i++)
{

std::cout << vec[i][0];
}
return EXIT_SUCCESS;
}

You can also use a range based for loop

for (auto &i : vec)
std::cout << i[0] << " ";

The output will be

c m p

Find index of vector element using search_n function

The std::search_n function looks for a sequence of a specified number of occurrences of a particular value in a range; that number is the third argument (count on this cppreference page).

So, if you insist on using std::search_n for this, you will need to add an extra argument (count, which will be 1) in your call:

it = std::search_n(a.begin(), a.begin() + n, 1, number);

However, using search_n is something of an overkill when looking for a single value; better to use the simpler (and faster) std::find function. Also, in place of a.begin() + n, you can use the easier and clearer a.end().

it = std::find(a.begin(), a.end(), number);

Also note that indexes and iterator positions in C++ start at zero, so, with the above fix(es) applied to your code, the answer will be "found at position 4"; if you want a 1-based position, then add 1 to the position; something like this:

auto position = std::distance(a.begin(), it) + 1;

Find index of element in vector of pairs

I would simply go with a normal for_each loop.

So:

int index = 0;
for(const auto& pair : dict) {
if(pair.first == <whatever>) {
break;
}
index++;
}

//if index == dict.size() then print element not found

Other way would be using std::find_if() ( Thanks @Tony Delroy :) )

auto index = std::distance(dict.begin(), std::find_if(dict.begin(), dict.end(), [&](const auto& pair) { return pair.first == movieName; }));


Related Topics



Leave a reply



Submit