C++98 中的容器初始化

Container initialization in C++98

我必须使用以下规则构建有序容器(必须是可迭代的):

If the condition is true, the container is {1,0}, else it's {0,1}

我有下面的代码,但是没找到"elegant":

   vector<int> orderedSides;
   if (condition) 
   {
       orderedSides.push_back(1);
       orderedSides.push_back(0);
   }
   else            
   {
       orderedSides.push_back(0);
       orderedSides.push_back(1);
   }

有没有更好的方法来做到这一点(从简洁和性能的角度来看)?

你可以这样实现:

vector<int> orderedSides(2, 0);
(condition ? orderedSides.front() : orderedSides.back()) = 1;

比显式 if 子句短一点。

正如下面@Deduplicator 提到的,我们可能会以更简洁的方式重写第二行:

orderedSides[!condition] = 1;
vector<int> orderedSides;
orderedSides.push_back(condition ? 1 : 0);
orderedSides.push_back(condition ? 0 : 1);

我不认为它的性能更高,但我觉得它更优雅。

orderedSides.push_back(0);
orderedSides.push_back(1);
if (condition)
  std::iter_swap(orderedSides.begin(), orderedSides.begin()+1);

我知道这需要比特成本。作为候选人之一。

您可以在效率和避免重复之间做出折衷,用条件初始化第一个,然后从第一个初始化第二个。

vector<int> orderedSides(1, bool(condition)) ;
orderedSides.push_back(!orderedSides.back());

即使在 C++98 中,您也可以从数组填充 std::vector

这是一个例子:

#include <iostream>
#include <vector>

int main() {
    bool condition = false;
    std::cout << "condition is: " << std::boolalpha << condition << '\n';

    int arr[][2] = {{0,1}, {1,0}};
    int index = condition;
    std::vector<int> v(arr[index], arr[index]+2);

    for (int i = 0; i < v.size(); i++)
        std::cout << v[i] << ' ';
    std::cout << '\n';
}

输出为:

$ g++ tt.cc && ./a.out
condition is: false
0 1 

供参考:

如果构建元素(您问题中的 ints,无论它在现实生活中是什么)是免费且无副作用的:

static const int data[] = { 0, 1, 0 };
std::vector<int> orderedSides (data+condition, data+condition+2);

完整程序示例:

#include <iostream>
#include <vector>

std::vector<int> make(bool cond)
{
    static const int data[] = { 0, 1, 0 };
    return std::vector<int> (data+cond, data+cond+2);
}

std::ostream& operator<<(std::ostream& os, const std::vector<int>& v)
{
    return os << "{ " << v[0] << ", " << v[1] << " }";
}    

int main()
{
    std::cout << "true:  " << make(true) << "\n"
              << "false: " << make(false) << "\n";
}

打印:

true:  { 1, 0 }
false: { 0, 1 }

Demo