Check if string element is not an element of a vector of strings

Mar 23, 2022 at 9:51am
How can I check if a string isn´t an element of a vector of strings. The idea is, if the current string isn´t an element of that vector, it should be added to it.
I tried using a for loop, but apprently I somehow got it wrong. Here is what I did:

for (int i = 0; i < operations.size(); i++){
if (entry != operations[i]){
operations.push_back(entry);
results.push_back(temp);
}
else{
entry.clear();
}
}
Mar 23, 2022 at 10:14am
BJKY0712 wrote:
1
2
3
4
5
6
7
8
9
for (int i = 0; i < operations.size(); i++){
	if (entry != operations[i]){
		operations.push_back(entry);
		results.push_back(temp);
	}
	else{
		entry.clear();
	}
}

It looks like you're trying to do two things at the same time, (1) check if the vector contains the string, and (2) insert the string. It's easier to get right if you treat these as two separate steps.

I suggest you write a loop that only has the one purpose to check if the string is inside the vector or not (you might want to put this into a separate function). Then you can use the result of that loop (or function) to decide whether you should add the string to the vector.
Last edited on Mar 23, 2022 at 10:20am
Mar 23, 2022 at 1:51pm
Something like:

1
2
3
4
const auto itr {std::find(operations.begin(), operations.end(), entry)};

if (itr == operations.end())
    operations.push_back(entry);


Have you considered using a std::set instead?
Last edited on Mar 23, 2022 at 2:14pm
Topic archived. No new replies allowed.