2
\$\begingroup\$

I want a second copy of an std::vector in which all elements are inverted, e.g. 0x01 in the first vector should be 0xFE in the second.

Is this a good solution?

std::vector<uint8_t> first_list = {0x01, 0x10, 0x32, 0x1A };
std::vector<uint8_t> second_list = first_list;
for(std::vector<uint8_t>::iterator it = second_list.begin(); it != second_list.end(); ++it)
 *it = ~*it;

The for loop sticks out to me as unnecessarily verbose.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 3, 2013 at 8:22
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

You can use the new for() in C++11

std::vector<uint8_t> first_list = {0x01, 0x10, 0x32, 0x1A};
std::vector<uint8_t> second; 
for(uint8_t& it: first_list)
{ second.push_back(~it);
}
answered Oct 3, 2013 at 15:51
\$\endgroup\$
1
  • \$\begingroup\$ This kind of for loop is what I've been wishing for every time I've written one with an explicitly incrementing iterator! \$\endgroup\$ Commented Oct 4, 2013 at 9:04
4
\$\begingroup\$

You can utilize std::transform here (I'll assume C++11 for the lambda):

int main()
{
 std::vector<uint8_t> first_list = {0x01, 0x10, 0x32, 0x1A};
 std::vector<uint8_t> second; 
 std::transform(first_list.begin(), first_list.end(), std::back_inserter(second),
 [](uint8_t u) { return ~u; });
}

You also don't need to make a copy of the first vector to do this; better to simply use push_back (or back_inserter here, since we're working with iterators).

answered Oct 3, 2013 at 8:37
\$\endgroup\$
1
  • \$\begingroup\$ Frankly, written out as a for loop is kind of less code than using transform with a lambda. \$\endgroup\$ Commented Oct 4, 2013 at 0:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.